package org.jeecg.modules.wlhy.shipping.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.EntityDict;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.PayConstants;
import org.jeecg.common.constant.enums.MessageTypeEnum;
import org.jeecg.common.constant.enums.ReportPlatformEnum;
import org.jeecg.common.constant.enums.ShippingTyeEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.ExcelUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.paycenter.enums.BillTypeEnum;
import org.jeecg.modules.paycenter.service.BillService;
import org.jeecg.modules.system.constant.UserTypeEnum;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.third.amap.dto.RegeoDTO;
import org.jeecg.modules.third.amap.service.AmapService;
import org.jeecg.modules.third.amap.service.HyShippingNoteAmapService;
import org.jeecg.modules.third.kaiyunshukedaikai.KaiyunService;
import org.jeecg.modules.third.nucarf.GasService;
import org.jeecg.modules.third.openapi.WaybillRouteService;
import org.jeecg.modules.wlhy.bill.entity.HyBill;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.service.IHyBillService;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.company.entity.HyCompanyConfig;
import org.jeecg.modules.wlhy.company.service.IHyCompanyConfigService;
import org.jeecg.modules.wlhy.customer.entity.*;
import org.jeecg.modules.wlhy.customer.service.*;
import org.jeecg.modules.wlhy.enterprise.entity.HyEnterprise;
import org.jeecg.modules.wlhy.gas.entity.HyShippingNoteGas;
import org.jeecg.modules.wlhy.gas.service.IHyShippingNoteGasService;
import org.jeecg.modules.wlhy.hyarea.entity.HyArea;
import org.jeecg.modules.wlhy.hyarea.service.IHyAreaService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydriverbank.entity.HyDriverBank;
import org.jeecg.modules.wlhy.hydriverbank.service.IHyDriverBankService;
import org.jeecg.modules.wlhy.hydrivercustomer.service.IHyDriverCustomerService;
import org.jeecg.modules.wlhy.hyevent.constant.AhRealtimeEnum;
import org.jeecg.modules.wlhy.hyevent.event.AhRealtimeReportEvent;
import org.jeecg.modules.wlhy.hyevent.event.HistoryTraceEvent;
import org.jeecg.modules.wlhy.hyevent.event.ShippingNoticeEvent;
import org.jeecg.modules.wlhy.hyinsurance.dto.InsuranceApplyDto;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyDriverVehicle;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyDriverVehicleService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.hyzyb.service.IHyZybService;
import org.jeecg.modules.wlhy.invoice.entity.HyInvoice;
import org.jeecg.modules.wlhy.invoice.entity.HyInvoiceDTO;
import org.jeecg.modules.wlhy.invoice.entity.HyInvoiceDTO3;
import org.jeecg.modules.wlhy.invoice.service.IHyInvoiceService;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.order.entity.HyOrderDTO;
import org.jeecg.modules.wlhy.order.entity.HyOrderReceiveAddress;
import org.jeecg.modules.wlhy.order.entity.HyOrderSendAddress;
import org.jeecg.modules.wlhy.order.service.IHyOrderReceiveAddressService;
import org.jeecg.modules.wlhy.order.service.IHyOrderSendAddressService;
import org.jeecg.modules.wlhy.order.service.IHyOrderService;
import org.jeecg.modules.wlhy.order.vo.HyOrderVO;
import org.jeecg.modules.wlhy.report.ShippingNoteApiAlct56Service;
import org.jeecg.modules.wlhy.report.impl.*;
import org.jeecg.modules.wlhy.setting.entity.HySetting;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.shipping.constant.ShippingPayStatus;
import org.jeecg.modules.wlhy.shipping.constant.ShippingStatus;
import org.jeecg.modules.wlhy.shipping.dto.ImportUpdateShippingNoteDTO;
import org.jeecg.modules.wlhy.shipping.entity.*;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteHistoryService;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteReceiveAddressService;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteSendAddressService;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.shipping.service.impl.HyShippingExcelExportImpl;
import org.jeecg.modules.wlhy.shipping.vo.HyShippingNoteVO;
import org.jeecg.modules.wlhy.shipping.vo.ZybShippingNoteVO;
import org.jeecg.modules.wlhy.utils.*;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 运单表
 * @Author: jeecg-boot
 * @Date: 2020-12-05
 * @Version: V1.0
 */
@Api(tags = "运单表")
@RestController
@RequestMapping("/shipping/hyShippingNote")
//@RequiresRoles(value={"admin", "customer", "driver"},logical = Logical.OR)
@Slf4j
public class HyShippingNoteController extends JeecgController<HyShippingNote, IHyShippingNoteService> {
    @Autowired
    private IHyShippingNoteService hyShippingNoteService;
    @Autowired
    private IHyShippingNoteBillService hyShippingNoteBillService;
    @Autowired
    private UserUtil userUtil;
    @Autowired
    private IHyAreaService hyAreaService;
    @Autowired
    private IHyDriverService hyDriverService;
    @Autowired
    private IHyDriverBankService hyDriverBankService;
    @Autowired
    private IHyShippingNoteHistoryService hyShippingNoteHistoryService;
    @Autowired
    private IHySettingService settingService;
    @Autowired
    private IHyVehicleService hyVehicleService;
    @Autowired
    private IHyShippingNoteGasService hyShippingNoteGasService;
    @Autowired
    private IHyCompanyConfigService companyConfigService;
    @Autowired
    private IHyOrderService hyOrderService;
    @Autowired
    private IHyShippingNoteSendAddressService hyShippingNoteSendAddressService;
    @Autowired
    private IHyShippingNoteReceiveAddressService hyShippingNoteReceiveAddressService;
    @Autowired
    private IHyOrderService iHyOrderService;
    @Autowired
    private IHyInvoiceService hyInvoiceService;
    @Autowired
    private GasService gasService;

    @Autowired
    private WaybillRouteService waybillRouteService;

    @Autowired
    private HyShippingNoteAmapService shippingNoteAmapService;

    @Autowired
    private IHyDriverVehicleService hyDriverVehicleService;
    @Autowired
    private IHyBillService hyBillService;

    @Autowired
    private IHyCustomerConfigService customerConfigService;

    @Value(value = "${spring.profiles.active}")
    private String activeProfile;

    @Autowired
    private ProjectUtil projectUtil;
    @Autowired
    private IHyDriverCustomerService hyDriverCustomerService;
    @Autowired
    private IHyCustomerCompanyService hyCustomerCompanyService;
    @Autowired
    private IHyOrderSendAddressService hyOrderSendAddressService;
    @Autowired
    private IHyOrderReceiveAddressService hyOrderReceiveAddressService;

    @Autowired
    private BillService billService;

    @Autowired
    private IHyZybService zybService;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;


    @Autowired
    private ShippingNoteApiAlct56Service shippingNoteApiAlct56Service;


    @Autowired
    private IHyCustomerService customerService;

    @Autowired
    private IHyCustomerAddressSendService customerAddressSendService;

    @Autowired
    private IHyCustomerAddressReceiveService customerAddressReceiveService;


    @Autowired
    private RedisUtil redisUtil;




    //region 基本

    @ApiOperation(value = "运单表-分页列表查询", notes = "运单表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HyShippingNote hyShippingNote,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HyShippingNote> queryWrapper = QueryGenerator.initQueryWrapper(hyShippingNote, req.getParameterMap());

        //如果传了zybflag，表示要查询有智运宝设备的运单
        if (ObjectUtil.isNotEmpty(hyShippingNote.getZybShippingFlag())) {
            queryWrapper.isNotNull("vehicle_device");
        } else {
            queryWrapper.isNull("vehicle_device");
        }

        projectUtil.setQueryWrapperByProject("customer_id", queryWrapper);
        if (userUtil.isCaptain()){
            List<String> hyVehicleIdList = userUtil.getHyVehicleIdList();
            if (hyVehicleIdList.size()!= 0) {
                queryWrapper.in("hy_shipping_note.vehicle_id", hyVehicleIdList);
            } else {
                return Result.OK();
            }
        }
        Page<HyShippingNote> page = new Page<HyShippingNote>(pageNo, pageSize);
        IPage<HyShippingNote> pageList = hyShippingNoteService.page(page, queryWrapper);


//		List<HyShippingNote> hyShippingNotes = pageList.getRecords().stream().collect(toList());
        List<HyShippingNote> hyShippingNotes = pageList.getRecords();

        //查询司机
        if (CollectionUtils.isNotEmpty(hyShippingNotes)) {
            List<String> driverIds = hyShippingNotes.stream().map(
                    item -> item.getDriverId()
            ).distinct().filter(Objects::nonNull).collect(Collectors.toList());

            if (CollUtil.isNotEmpty(driverIds)) {
                List<HyDriver> drivers = hyDriverService.listByIds(driverIds);

                Map<String, String> driversMaps = drivers.stream().collect(
                        Collectors.toMap(HyDriver::getId, HyDriver::getTelephone, (key1, key2) -> key2)
                );
                for (HyShippingNote shippingNote : hyShippingNotes) {
                    shippingNote.setTelephone1(driversMaps.get(shippingNote.getDriverId()));
                }
//            pageList.setRecords(hyShippingNotes);
            }
        }

        return Result.OK(pageList);
    }

    private void setQueryWrapper(HyShippingNoteDTO shippingNoteDTO, QueryWrapper<HyShippingNoteDTO> queryWrapper) {


        String kyState = shippingNoteDTO.getKyState();
        if (StringUtils.isNotEmpty(kyState)) {
            if (kyState.equals("0")) {//待上报

                queryWrapper.eq("hy_shipping_note.shipping_pay_status","6");
                queryWrapper.ne("hy_shipping_note.ky_state", "1");

            }
            if (kyState.equals("1")) {//成功
                queryWrapper.eq("hy_shipping_note.ky_state", "1");
            }

        }


        String shippingPayStatus = shippingNoteDTO.getShippingPayStatus();


        if (StringUtils.isNotEmpty(shippingPayStatus)) {
            if (shippingPayStatus.indexOf("!") == 0) {
                shippingPayStatus = shippingPayStatus.substring(1, shippingPayStatus.length());
                queryWrapper.ne("hy_shipping_note.shipping_pay_status", shippingPayStatus);
            } else {
                if (shippingPayStatus.contains(",")) {
                    queryWrapper.in("hy_shipping_note.shipping_pay_status", Arrays.asList(shippingPayStatus.split(",")));
                } else {
                    queryWrapper.eq("hy_shipping_note.shipping_pay_status", shippingPayStatus);
                }
            }
        }


        if (StringUtils.isNotEmpty(shippingNoteDTO.getSendAddress())) {
            queryWrapper.like("hy_shipping_note.send_address", shippingNoteDTO.getSendAddress());
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getReceiveAddress())) {
            queryWrapper.like("hy_shipping_note.receive_address", shippingNoteDTO.getReceiveAddress());
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getSendAddressName())) {
            queryWrapper.like("hy_shipping_note.send_address_name", shippingNoteDTO.getSendAddressName());
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getReceiveAddressName())) {
            queryWrapper.like("hy_shipping_note.receive_address_name", shippingNoteDTO.getReceiveAddressName());
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getKhdh())) {
            queryWrapper.like("hy_shipping_note.khdh", shippingNoteDTO.getKhdh());
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getContractNum2())) {
            queryWrapper.eq("hy_shipping_note.contract_num2", shippingNoteDTO.getContractNum2());
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getContractStatus())) {
            queryWrapper.eq("hy_shipping_note.contract_status", shippingNoteDTO.getContractStatus());
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getOrderId())) {
            queryWrapper.eq("hy_shipping_note.order_id", shippingNoteDTO.getOrderId());
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getCompanyId())) {
            queryWrapper.eq("hy_shipping_note.company_id", shippingNoteDTO.getCompanyId());
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getShippingStatus())) {
            queryWrapper.eq("hy_shipping_note.shipping_status", shippingNoteDTO.getShippingStatus());
        }

        //Added start at 2024-04-10 for 筛选是否生成运输合同
        if (StringUtils.isNotEmpty(shippingNoteDTO.getContractCreated())) {
            //0未生成，判断null和字符串空
            if ("0".equals(shippingNoteDTO.getContractCreated())) {
                queryWrapper.nested(
                        qw->qw.isNull("hy_shipping_note.shipping_contract")
                                .or().eq("hy_shipping_note.shipping_contract", ""));
            } else if ("1".equals(shippingNoteDTO.getContractCreated())) {
                queryWrapper.isNotNull("hy_shipping_note.shipping_contract");
                queryWrapper.ne("hy_shipping_note.shipping_contract", "");
            }

            queryWrapper.ne("hy_shipping_note.shipping_status", "8");
        }
        //Added end at 2024-04-10 for 筛选是否生成运输合同

        String orderMode = shippingNoteDTO.getOrderMode();
        if (StringUtils.isNotEmpty(orderMode)) {
            if (orderMode.contains(",")) {
                queryWrapper.in("hy_shipping_note.order_mode", Arrays.asList(orderMode.split(",")));
            } else {
                queryWrapper.eq("hy_shipping_note.order_mode", orderMode);
            }
        }
        String payChannel = shippingNoteDTO.getPayChannel();
        if (StringUtils.isNotEmpty(payChannel)) {
            if (payChannel.contains(",")) {
                queryWrapper.in("hy_shipping_note.pay_channel", Arrays.asList(payChannel.split(",")));
            } else {
                queryWrapper.eq("hy_shipping_note.pay_channel", shippingNoteDTO.getPayChannel());
            }
        }
        //道达推送筛选条件
//		if(StringUtils.isNotEmpty(shippingNoteDTO.getDaoDaType())){
//			//撮合模式
//			queryWrapper.eq("hy_shipping_note.order_mode","2");
//			//货主宏瑞 河北公司
//			queryWrapper.or()
//					.eq("hy_shipping_note.customer_id","1382219981252464642")
//			        .eq("hy_shipping_note.company_id","1412945342084681729");
//		}else{
//			queryWrapper.eq("hy_shipping_note.order_mode",orderMode);
//		}

        if (StringUtils.isNotEmpty(shippingNoteDTO.getDaodaUploadStatus())) {
            queryWrapper.eq("hy_shipping_note.daoda_upload_status", shippingNoteDTO.getDaodaUploadStatus());
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getUploadNucarEtc())) {
            queryWrapper.eq("hy_shipping_note.upload_nucar_etc", shippingNoteDTO.getUploadNucarEtc());
        }


//		if(StringUtils.isNotEmpty(shippingNoteDTO.getBillStatus())){
//			queryWrapper.eq("hy_shipping_note.bill_status",shippingNoteDTO.getBillStatus());
//		}
        if (StringUtils.isNotEmpty(shippingNoteDTO.getAlctIdentification())) {
            queryWrapper.eq("hy_shipping_note.alct_identification", shippingNoteDTO.getAlctIdentification());
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getTosIdentification())) {
            queryWrapper.eq("hy_shipping_note.tos_identification", shippingNoteDTO.getTosIdentification());
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getUploadStatus())) {
            queryWrapper.eq("hy_shipping_note.upload_status", shippingNoteDTO.getUploadStatus());
        }


        if (StringUtils.isNotEmpty(shippingNoteDTO.getBillStatus())) {
            queryWrapper.in("hy_shipping_note.bill_status", Arrays.asList(shippingNoteDTO.getBillStatus().split(",")));
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getDriverName())) {
            queryWrapper.like("d.driver_name", shippingNoteDTO.getDriverName());
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getTelephone())) {
            queryWrapper.like("d.telephone", shippingNoteDTO.getTelephone());
        }


        if (StringUtils.isNotEmpty(shippingNoteDTO.getVehicleNumber())) {
            queryWrapper.like("v.vehicle_number", shippingNoteDTO.getVehicleNumber());
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getShippingNoteNumber())) {
            queryWrapper.like("hy_shipping_note.shipping_note_number", shippingNoteDTO.getShippingNoteNumber());
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getDescriptionOfGoods())) {
            queryWrapper.like("hy_shipping_note.description_of_goods", shippingNoteDTO.getDescriptionOfGoods());
        }


        if (StringUtils.isNotEmpty(shippingNoteDTO.getCreateTime_begin())) {
            queryWrapper.ge("hy_shipping_note.create_time", shippingNoteDTO.getCreateTime_begin() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getCreateTime_end())) {
            queryWrapper.le("hy_shipping_note.create_time", shippingNoteDTO.getCreateTime_end() + " 23:59:59");
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getStatusDtUnloading_begin())) {
            queryWrapper.ge("hy_shipping_note.status_dt_unloading", shippingNoteDTO.getStatusDtUnloading_begin() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getStatusDtUnloading_end())) {
            queryWrapper.le("hy_shipping_note.status_dt_unloading", shippingNoteDTO.getStatusDtUnloading_end() + " 23:59:59");
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getStatusDtReceive_begin())) {
            queryWrapper.ge("hy_shipping_note.status_dt_receive", shippingNoteDTO.getStatusDtReceive_begin() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getStatusDtReceive_end())) {
            queryWrapper.le("hy_shipping_note.status_dt_receive", shippingNoteDTO.getStatusDtReceive_end() + " 23:59:59");
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getStatusDtLoading_begin())) {
            queryWrapper.ge("hy_shipping_note.status_dt_loading", shippingNoteDTO.getStatusDtLoading_begin() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getStatusDtLoading_end())) {
            queryWrapper.le("hy_shipping_note.status_dt_loading", shippingNoteDTO.getStatusDtLoading_end() + " 23:59:59");
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getStatusDtSign_begin())) {
            queryWrapper.ge("hy_shipping_note.status_dt_sign", shippingNoteDTO.getStatusDtSign_begin() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getStatusDtSign_end())) {
            queryWrapper.le("hy_shipping_note.status_dt_sign", shippingNoteDTO.getStatusDtSign_end() + " 23:59:59");
        }


        if (StringUtils.isNotEmpty(shippingNoteDTO.getTaxUploadDate_begin())) {
            queryWrapper.ge("hy_shipping_note.tax_upload_date", shippingNoteDTO.getTaxUploadDate_begin() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getTaxUploadDate_end())) {
            queryWrapper.le("hy_shipping_note.tax_upload_date", shippingNoteDTO.getTaxUploadDate_end() + " 23:59:59");
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getPayDt_begin())) {
            queryWrapper.ge("hy_shipping_note.pay_dt", shippingNoteDTO.getPayDt_begin() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getPayDt_end())) {
            queryWrapper.le("hy_shipping_note.pay_dt", shippingNoteDTO.getPayDt_end() + " 23:59:59");
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getPayDtCheck_begin())) {
            queryWrapper.ge("hy_shipping_note.pay_dt_check", shippingNoteDTO.getPayDtCheck_begin());
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getPayDtCheck_end())) {
            queryWrapper.le("hy_shipping_note.pay_dt_check", shippingNoteDTO.getPayDtCheck_end());
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getPayDtSubmitAut_begin())) {
            queryWrapper.ge("hy_shipping_note.pay_dt_submit_aut", shippingNoteDTO.getPayDtSubmitAut_begin() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getPayDtSubmitAut_end())) {
            queryWrapper.le("hy_shipping_note.pay_dt_submit_aut", shippingNoteDTO.getPayDtSubmitAut_end() + " 23:59:59");
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getCarrierId())) {
            queryWrapper.eq("hy_shipping_note.carrier_id", shippingNoteDTO.getCarrierId());
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getIntroducer())) {
            queryWrapper.like("hy_shipping_note.introducer", shippingNoteDTO.getIntroducer());
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getDispatcher())) {
            queryWrapper.like("hy_shipping_note.dispatcher", shippingNoteDTO.getDispatcher());
        }
        //预付
        if (StringUtils.isNotEmpty(shippingNoteDTO.getPrePayStatus())) {
            queryWrapper.eq("hy_shipping_note.pre_pay_status", shippingNoteDTO.getPrePayStatus());
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getPayType())) {
            queryWrapper.eq("hy_shipping_note.pay_type", shippingNoteDTO.getPayType());
        }

        //增加开票完成时间段查询
        if (StringUtils.isNotEmpty(shippingNoteDTO.getBillDtComplateBegin())) {
            queryWrapper.ge("hy_shipping_note.bill_dt_complate", shippingNoteDTO.getBillDtComplateBegin());
        }
        if (StringUtils.isNotEmpty(shippingNoteDTO.getBillDtComplateEnd())) {
            queryWrapper.le("hy_shipping_note.bill_dt_complate", shippingNoteDTO.getBillDtComplateEnd());
        }

    }

    @ApiOperation(value = "运单表管理模式-分页列表查询", notes = "运单表管理模式-分页列表查询")
    @GetMapping(value = "/newlist")
    public Result<?> queryPageNewList(HyShippingNoteDTO shippingNoteDTO,
                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        QueryWrapper<HyShippingNoteDTO> queryWrapper = new QueryWrapper();

        String shippingPayStatus = shippingNoteDTO.getShippingPayStatus();
        if (userUtil.isSys()) {
            if (StringUtils.isNotEmpty(shippingNoteDTO.getCustomerId())) {
                queryWrapper.eq("hy_shipping_note.customer_id", shippingNoteDTO.getCustomerId());
            }
        } else if (userUtil.isCustomerAdmin()) {
            queryWrapper.in("hy_shipping_note.customer_id", userUtil.getCustomerAdminRelationIdList());
        } else if (userUtil.isCaptain()) {
            List<String> hyVehicleIdList = userUtil.getHyVehicleIdList();
            if (hyVehicleIdList.size()!= 0) {
                queryWrapper.in("hy_shipping_note.vehicle_id", hyVehicleIdList);
            } else {
                return Result.OK();
            }
        }else{
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                throw new JeecgBootException("货主信息不存在!");
            }
            if (StringUtils.isNotEmpty(shippingNoteDTO.getCustomerId())) {
                queryWrapper.eq("hy_shipping_note.customer_id", shippingNoteDTO.getCustomerId());
                queryWrapper.eq("hy_shipping_note.agent_id", customer.getId());
            } else {
                if ("4".equals(shippingPayStatus) || "7".equals(shippingPayStatus)) {
                    queryWrapper.eq("hy_shipping_note.customer_id", customer.getId());
                } else {
                    queryWrapper.and(
                            qw -> qw.eq("hy_shipping_note.customer_id", customer.getId())
                                    .or()
                                    .eq("hy_shipping_note.agent_id", customer.getId()));
                }
            }
        }
        setQueryWrapper(shippingNoteDTO, queryWrapper);
        queryWrapper.eq("hy_shipping_note.del_flag", "0");

        //TODO 这里将来要把智运宝的运单拆出去，变成新接口
        //运单列表中不展示智运宝的运单
        //queryWrapper.isNull("hy_shipping_note.vehicle_device");

        //Added at 2023-08-21 for 货源号搜索,货源号搜索时的前提是没有货源id搜索条件
        if (StringUtils.isEmpty(shippingNoteDTO.getOrderId()) && StringUtils.isNotEmpty(shippingNoteDTO.getOrderNum())) {
            List<HyOrder> hyOrderList = this.hyOrderService.list(new LambdaQueryWrapper<HyOrder>().like(HyOrder::getOrderNum, shippingNoteDTO.getOrderNum()));
            if (CollUtil.isNotEmpty(hyOrderList)) {
                List<String> ids = hyOrderList.stream().map(HyOrder::getId).collect(Collectors.toList());
                queryWrapper.in("hy_shipping_note.order_id", ids);
            } else {
                return Result.OK();
            }
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getKeyword())) {
            queryWrapper.and(
                    qw -> qw.like("d.driver_name", shippingNoteDTO.getKeyword())
                            .or()
                            .like("v.vehicle_number", shippingNoteDTO.getKeyword()));
        }

        String byDesc = shippingNoteDTO.getByDesc();
        if (StringUtils.isNotEmpty(byDesc)) {
            String[] bys = byDesc.split(",");
            for (String by : bys) {
                queryWrapper.orderByDesc("hy_shipping_note." + by);
            }

        } else {
            queryWrapper.orderByDesc("hy_shipping_note.status_dt_unloading");
        }
        queryWrapper.groupBy("hy_shipping_note.id");

        Page<HyShippingNoteDTO> page = new Page<HyShippingNoteDTO>(pageNo, pageSize);
        IPage<HyShippingNoteDTO> pageList = hyShippingNoteService.getPageList(page, queryWrapper);

        //如果开启系统脱敏
        String dataMaskingFlag = this.settingService.getSettingValueByTag("data_masking");
        if ("1".equals(dataMaskingFlag)) {
            for (HyShippingNoteDTO dto : pageList.getRecords()) {
                dto.setTelephone(DataMaskingUtil.phoneMasking(dto.getTelephone()));
                dto.setSjsfzh(DataMaskingUtil.idcardMasking(dto.getSjsfzh()));
                dto.setSjyhkh(DataMaskingUtil.bankNumberMasking(dto.getSjyhkh()));
            }
        }

        return Result.OK(pageList);
    }
    @ApiOperation(value = "运单表管理模式-分页列表查询", notes = "运单表管理模式-分页列表查询")
    @GetMapping(value = "/newlist2")
    public Result<?> queryPageNewList2(HyShippingNoteDTO shippingNoteDTO,
                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        QueryWrapper<HyShippingNoteDTO> queryWrapper = new QueryWrapper();
        String shippingPayStatus = shippingNoteDTO.getShippingPayStatus();
        if (userUtil.isSys()) {
            if (StringUtils.isNotEmpty(shippingNoteDTO.getCustomerId())) {
                queryWrapper.eq("hy_shipping_note.customer_id", shippingNoteDTO.getCustomerId());
            }
        } else if (userUtil.isCustomerAdmin()) {
            queryWrapper.in("hy_shipping_note.customer_id", userUtil.getCustomerAdminRelationIdList());
        } else {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                throw new JeecgBootException("货主信息不存在!");
            }
            if (StringUtils.isNotEmpty(shippingNoteDTO.getCustomerId())) {
                queryWrapper.eq("hy_shipping_note.customer_id", shippingNoteDTO.getCustomerId());
                queryWrapper.eq("hy_shipping_note.agent_id", customer.getId());
            } else {
                if ("4".equals(shippingPayStatus) || "7".equals(shippingPayStatus)) {
                    queryWrapper.eq("hy_shipping_note.customer_id", customer.getId());
                } else {
                    queryWrapper.and(
                            qw -> qw.eq("hy_shipping_note.customer_id", customer.getId())
                                    .or()
                                    .eq("hy_shipping_note.agent_id", customer.getId()));
                }
            }
        }
        setQueryWrapper(shippingNoteDTO, queryWrapper);
        queryWrapper.eq("hy_shipping_note.del_flag", "0");

        //TODO 这里将来要把智运宝的运单拆出去，变成新接口
        //运单列表中不展示智运宝的运单
        //queryWrapper.isNull("hy_shipping_note.vehicle_device");

        //Added at 2023-08-21 for 货源号搜索,货源号搜索时的前提是没有货源id搜索条件
        if (StringUtils.isEmpty(shippingNoteDTO.getOrderId()) && StringUtils.isNotEmpty(shippingNoteDTO.getOrderNum())) {
            List<HyOrder> hyOrderList = this.hyOrderService.list(new LambdaQueryWrapper<HyOrder>().like(HyOrder::getOrderNum, shippingNoteDTO.getOrderNum()));
            if (CollUtil.isNotEmpty(hyOrderList)) {
                List<String> ids = hyOrderList.stream().map(HyOrder::getId).collect(Collectors.toList());
                queryWrapper.in("hy_shipping_note.order_id", ids);
            } else {
                return Result.OK();
            }
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getKeyword())) {
            queryWrapper.and(
                    qw -> qw.like("d.driver_name", shippingNoteDTO.getKeyword())
                            .or()
                            .like("v.vehicle_number", shippingNoteDTO.getKeyword()));
        }

        String byDesc = shippingNoteDTO.getByDesc();
        if (StringUtils.isNotEmpty(byDesc)) {
            String[] bys = byDesc.split(",");
            for (String by : bys) {
                queryWrapper.orderByDesc("hy_shipping_note." + by);
            }

        } else {
            queryWrapper.orderByDesc("hy_shipping_note.create_time");
        }
        queryWrapper.groupBy("hy_shipping_note.id");

        Page<HyShippingNoteDTO> page = new Page<HyShippingNoteDTO>(pageNo, pageSize);
        IPage<HyShippingNoteDTO> pageList = hyShippingNoteService.getPageList(page, queryWrapper);

        //如果开启系统脱敏
        String dataMaskingFlag = this.settingService.getSettingValueByTag("data_masking");
        if ("1".equals(dataMaskingFlag)) {
            for (HyShippingNoteDTO dto : pageList.getRecords()) {
                dto.setTelephone(DataMaskingUtil.phoneMasking(dto.getTelephone()));
                dto.setSjsfzh(DataMaskingUtil.idcardMasking(dto.getSjsfzh()));
                dto.setSjyhkh(DataMaskingUtil.bankNumberMasking(dto.getSjyhkh()));
            }
        }

        return Result.OK(pageList);
    }



    //Added at 2023-10-21 for 单独写一个申请开票菜单接口，不用运单查询接口了
    @ApiOperation(value = "运单表管理模式-分页列表查询", notes = "运单表管理模式-分页列表查询")
    @GetMapping(value = "/invoicelist")
    public Result<?> queryInvoiceList(HyShippingNoteDTO shippingNoteDTO,
                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        QueryWrapper<HyShippingNoteDTO> queryWrapper = new QueryWrapper();
        //String shippingPayStatus = shippingNoteDTO.getShippingPayStatus();

        //发票接口默认取支付完成的运单，如果invoicedFlag=1时表示开启了先票后款。
        String invoicedFlag = this.settingService.getSettingValueByTag("invoiced_before_payment");
        if ("1".equals(invoicedFlag)) {
            shippingNoteDTO.setShippingPayStatus("4,5,6");
        } else {
            shippingNoteDTO.setShippingPayStatus("6");
        }

        if (userUtil.isSys()) {
            if (StringUtils.isNotEmpty(shippingNoteDTO.getCustomerId())) {
                queryWrapper.eq("hy_shipping_note.customer_id", shippingNoteDTO.getCustomerId());
            }
        } else if (userUtil.isCustomerAdmin()) {
            queryWrapper.in("hy_shipping_note.customer_id", userUtil.getCustomerAdminRelationIdList());
        } else {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                throw new JeecgBootException("货主信息不存在!");
            }

            if (StringUtils.isNotEmpty(shippingNoteDTO.getCustomerId())) {
                queryWrapper.eq("hy_shipping_note.customer_id", shippingNoteDTO.getCustomerId());
                queryWrapper.eq("hy_shipping_note.agent_id", customer.getId());
            } else {
//                if ("4".equals(shippingPayStatus) || "7".equals(shippingPayStatus)) {
//                    queryWrapper.eq("hy_shipping_note.customer_id", customer.getId());
//                } else {
                queryWrapper.and(
                        qw -> qw.eq("hy_shipping_note.customer_id", customer.getId())
                                .or()
                                .eq("hy_shipping_note.agent_id", customer.getId()));
//                }
            }
        }
        setQueryWrapper(shippingNoteDTO, queryWrapper);
        queryWrapper.eq("hy_shipping_note.del_flag", "0");


//        //Added at 2023-08-21 for 货源号搜索,货源号搜索时的前提是没有货源id搜索条件
//        if (StringUtils.isEmpty(shippingNoteDTO.getOrderId()) && StringUtils.isNotEmpty(shippingNoteDTO.getOrderNum())) {
//            List<HyOrder> hyOrderList = this.hyOrderService.list(new LambdaQueryWrapper<HyOrder>().like(HyOrder::getOrderNum, shippingNoteDTO.getOrderNum()));
//            if (CollUtil.isNotEmpty(hyOrderList)) {
//                List<String> ids = hyOrderList.stream().map(HyOrder::getId).collect(Collectors.toList());
//                queryWrapper.in("hy_shipping_note.order_id", ids);
//            } else {
//                return Result.OK();
//            }
//        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getKeyword())) {
            queryWrapper.and(
                    qw -> qw.like("d.driver_name", shippingNoteDTO.getKeyword())
                            .or()
                            .like("v.vehicle_number", shippingNoteDTO.getKeyword()));
        }

        String byDesc = shippingNoteDTO.getByDesc();
        if (StringUtils.isNotEmpty(byDesc)) {
            String[] bys = byDesc.split(",");
            for (String by : bys) {
                queryWrapper.orderByDesc("hy_shipping_note." + by);
            }
        } else {
            queryWrapper.orderByDesc("hy_shipping_note.create_time");
        }
        queryWrapper.groupBy("hy_shipping_note.id");

        Page<HyShippingNoteDTO> page = new Page<HyShippingNoteDTO>(pageNo, pageSize);
        IPage<HyShippingNoteDTO> pageList = hyShippingNoteService.getPageList(page, queryWrapper);
//
//        //如果开启系统脱敏
//        String dataMaskingFlag = this.settingService.getSettingValueByTag("data_masking");
//        if ("1".equals(dataMaskingFlag)) {
//            for (HyShippingNoteDTO dto : pageList.getRecords()) {
//                dto.setTelephone(DataMaskingUtil.phoneMasking(dto.getTelephone()));
//                dto.setSjsfzh(DataMaskingUtil.idcardMasking(dto.getSjsfzh()));
//                dto.setSjyhkh(DataMaskingUtil.bankNumberMasking(dto.getSjyhkh()));
//            }
//        }

        return Result.OK(pageList);
    }


    @ApiOperation(value = "智运宝模式-分页列表查询", notes = "智运宝模式-分页列表查询")
    @GetMapping(value = "/zybNewlist")
    public Result<?> queryPageZybNewlist(HyShippingNoteDTO shippingNoteDTO,
                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        QueryWrapper<HyShippingNoteDTO> queryWrapper = new QueryWrapper();

        String shippingPayStatus = shippingNoteDTO.getShippingPayStatus();
        if (userUtil.isSys()) {
            if (StringUtils.isNotEmpty(shippingNoteDTO.getCustomerId())) {
                queryWrapper.eq("hy_shipping_note.customer_id", shippingNoteDTO.getCustomerId());
            }
        } else {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                throw new JeecgBootException("货主信息不存在!");
            }
            if (StringUtils.isNotEmpty(shippingNoteDTO.getCustomerId())) {
                queryWrapper.eq("hy_shipping_note.customer_id", shippingNoteDTO.getCustomerId());
                queryWrapper.eq("hy_shipping_note.agent_id", customer.getId());
            } else {
                if ("4".equals(shippingPayStatus) || "7".equals(shippingPayStatus)) {
                    queryWrapper.eq("hy_shipping_note.customer_id", customer.getId());
                } else {
                    queryWrapper.and(
                            qw -> qw.eq("hy_shipping_note.customer_id", customer.getId())
                                    .or()
                                    .eq("hy_shipping_note.agent_id", customer.getId()));
                }
            }
        }
        setQueryWrapper(shippingNoteDTO, queryWrapper);

        queryWrapper.eq("hy_shipping_note.del_flag", "0");
        queryWrapper.isNotNull("hy_shipping_note.vehicle_device");

        if (StringUtils.isNotEmpty(shippingNoteDTO.getKeyword())) {
            queryWrapper.and(
                    qw -> qw.like("d.driver_name", shippingNoteDTO.getKeyword())
                            .or()
                            .like("v.vehicle_number", shippingNoteDTO.getKeyword()));
        }

        String byDesc = shippingNoteDTO.getByDesc();
        if (StringUtils.isNotEmpty(byDesc)) {
            String[] bys = byDesc.split(",");
            for (String by : bys) {
                queryWrapper.orderByDesc("hy_shipping_note." + by);
            }

        } else {
            queryWrapper.orderByDesc("hy_shipping_note.create_time");
        }
        queryWrapper.groupBy("hy_shipping_note.id");

        Page<HyShippingNoteDTO> page = new Page<HyShippingNoteDTO>(pageNo, pageSize);
        IPage<HyShippingNoteDTO> pageList = hyShippingNoteService.getPageList(page, queryWrapper);

        if (CollUtil.isNotEmpty(pageList.getRecords())) {
            List<String> orderIds = pageList.getRecords().stream().filter(CommonUtils.distinctByKey(s -> s.getOrderId())).map(s -> s.getOrderId()).collect(Collectors.toList());

            QueryWrapper<HyOrderVO> orderQueryWrapper = new QueryWrapper();
            orderQueryWrapper.in("hy_order.id", orderIds);
            orderQueryWrapper.groupBy("hy_order.id");
            Page<HyOrderVO> orderPage = new Page<>(1, orderIds.size());
            IPage<HyOrderVO> orderPageList = this.hyOrderService.getPageList(orderPage, orderQueryWrapper);

            List<String> actualDriverIds = pageList.getRecords().stream().filter(s -> StrUtil.isNotEmpty(s.getActualDriverId()))
                    .filter(CommonUtils.distinctByKey(s -> s.getActualDriverId())).map(s -> s.getActualDriverId()).collect(Collectors.toList());

            List<HyDriver> actualDriverList;
            if (CollUtil.isNotEmpty(actualDriverIds)) {
                actualDriverList = this.hyDriverService.list(new LambdaQueryWrapper<HyDriver>().in(HyDriver::getId, actualDriverIds));
            } else {
                actualDriverList = null;
            }

            if (CollUtil.isNotEmpty(orderPageList.getRecords())) {
                pageList.getRecords().stream().forEach(s -> {
                            HyOrderVO vo = orderPageList.getRecords().stream().filter(o -> o.getId().equalsIgnoreCase(s.getOrderId())).findFirst().orElse(null);
                            if (null != vo) {
                                s.setTotalGoodsWeight(vo.getTotalGoodsWeight());
                                s.setFinishWeight(vo.getFinishWeight());
                                if (null != vo.getLeftWeight()) {
                                    s.setLeftWeight(vo.getLeftWeight().compareTo(BigDecimal.ZERO) < 1 ? BigDecimal.ZERO : vo.getLeftWeight());
                                } else {
                                    s.setLeftWeight(vo.getTotalGoodsWeight());
                                }
                            }

                            if (CollUtil.isNotEmpty(actualDriverList)) {
                                HyDriver actualDriver = actualDriverList.stream().filter(d -> d.getId().equals(s.getActualDriverId())).findAny().orElse(null);
                                if (null != actualDriver) {
                                    s.setActualDriverName(actualDriver.getDriverName());
                                }
                            }
                        }
                );
            }
        }

        return Result.OK(pageList);
    }


    @ApiOperation(value = "运单表管理模式-分页列表查询", notes = "运单表管理模式-分页列表查询")
    @GetMapping(value = "/checklist")
    public Result<?> queryPagecheckList(HyShippingNoteDTO shippingNoteDTO,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<HyShippingNoteDTO> queryWrapper = new QueryWrapper();
        String shippingPayStatus = shippingNoteDTO.getShippingPayStatus();
        if (userUtil.isSys()) {
            if (StringUtils.isNotEmpty(shippingNoteDTO.getCustomerId())) {
                queryWrapper.eq("hy_shipping_note.customer_id", shippingNoteDTO.getCustomerId());
            }
        } else if (userUtil.isCustomerAdmin()) {
            queryWrapper.in("hy_shipping_note.customer_id", userUtil.getCustomerAdminRelationIdList());
        } else {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                throw new JeecgBootException("货主信息不存在!");
            }
            if (StringUtils.isNotEmpty(shippingNoteDTO.getCustomerId())) {
                queryWrapper.eq("hy_shipping_note.customer_id", shippingNoteDTO.getCustomerId());
                queryWrapper.eq("hy_shipping_note.agent_id", customer.getId());
            } else {
                if ("4".equals(shippingPayStatus) || "7".equals(shippingPayStatus)) {
                    queryWrapper.eq("hy_shipping_note.customer_id", customer.getId());
                } else {
                    queryWrapper.and(
                            qw -> qw.eq("hy_shipping_note.customer_id", customer.getId())
                                    .or()
                                    .eq("hy_shipping_note.agent_id", customer.getId()));
                }
            }
        }
        setQueryWrapper(shippingNoteDTO, queryWrapper);
        queryWrapper.eq("hy_shipping_note.del_flag", "0");

        //Added at 2023-08-21 for 货源号搜索
        if (StringUtils.isNotEmpty(shippingNoteDTO.getOrderNum())) {
            List<HyOrder> hyOrderList = this.hyOrderService.list(new LambdaQueryWrapper<HyOrder>().like(HyOrder::getOrderNum, shippingNoteDTO.getOrderNum()));
            if (CollUtil.isNotEmpty(hyOrderList)) {
                List<String> ids = hyOrderList.stream().map(HyOrder::getId).collect(Collectors.toList());
                queryWrapper.in("hy_shipping_note.order_id", ids);
            } else {
                return Result.OK();
            }
        }

        if (StringUtils.isNotEmpty(shippingNoteDTO.getKeyword())) {
            queryWrapper.like("d.driver_name", shippingNoteDTO.getKeyword());
        }

        String byDesc = shippingNoteDTO.getByDesc();
        if (StringUtils.isNotEmpty(byDesc)) {
            String[] bys = byDesc.split(",");
            for (String by : bys) {
                queryWrapper.orderByDesc("hy_shipping_note." + by);
            }
        } else {
            queryWrapper.orderByDesc("hy_shipping_note.status_dt_unloading");
        }
        queryWrapper.groupBy("hy_shipping_note.id");

        Page<HyShippingNoteDTO> page = new Page<HyShippingNoteDTO>(pageNo, pageSize);
        IPage<HyShippingNoteDTO> pageList = hyShippingNoteService.getPageCheckList(page, queryWrapper);

        //如果开启系统脱敏
        String dataMaskingFlag = this.settingService.getSettingValueByTag("data_masking");
        if ("1".equals(dataMaskingFlag)) {
            for (HyShippingNoteDTO dto : pageList.getRecords()) {
                dto.setTelephone(DataMaskingUtil.phoneMasking(dto.getTelephone()));
                dto.setSjsfzh(DataMaskingUtil.idcardMasking(dto.getSjsfzh()));
                dto.setSjyhkh(DataMaskingUtil.bankNumberMasking(dto.getSjyhkh()));
            }
        }

        return Result.OK(pageList);
    }

    @ApiOperation(value = "代理运单表-分页列表查询", notes = "代理运单表-分页列表查询")
    @GetMapping(value = "/agentlist")
    public Result<?> queryPageAgentList(HyShippingNoteDTO shippingNoteDTO,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {

        HyCustomer customer = userUtil.getCustomer();
        if (customer == null) {
            throw new JeecgBootException("货主信息不存在!");
        }

        QueryWrapper<HyShippingNoteDTO> queryWrapper = new QueryWrapper();
        queryWrapper.eq("hy_shipping_note.agent_id", customer.getId());
        String customerId = shippingNoteDTO.getCustomerId();
        if (StringUtils.isNotEmpty(customerId)) {
            queryWrapper.eq("hy_shipping_note.customer_id", customerId);
        }

        setQueryWrapper(shippingNoteDTO, queryWrapper);
        queryWrapper.eq("hy_shipping_note.del_flag", "0");

        if (StringUtils.isNotEmpty(shippingNoteDTO.getKeyword())) {
            queryWrapper.like("d.driver_name", shippingNoteDTO.getKeyword());
        }

        String byDesc = shippingNoteDTO.getByDesc();
        if (StringUtils.isNotEmpty(byDesc)) {
            String[] bys = byDesc.split(",");
            for (String by : bys) {
                queryWrapper.orderByDesc("hy_shipping_note." + by);
            }
        } else {
            queryWrapper.orderByDesc("hy_shipping_note.create_time");
        }
        queryWrapper.groupBy("hy_shipping_note.id");

        Page<HyShippingNoteDTO> page = new Page<HyShippingNoteDTO>(pageNo, pageSize);
        IPage<HyShippingNoteDTO> pageList = hyShippingNoteService.getPageList(page, queryWrapper);
        return Result.OK(pageList);
    }

    //	@AutoLog(value = "运单表待评价-分页列表查询")
    @ApiOperation(value = "运单表待评价-分页列表查询", notes = "运单表待评价-分页列表查询")
    @GetMapping(value = "/elist")
    public Result<?> evaluateList(HyShippingNote hyShippingNote,
                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                  HttpServletRequest req) {
        QueryWrapper<HyShippingNote> queryWrapper = QueryGenerator.initQueryWrapper(hyShippingNote, req.getParameterMap());
        HyCustomer customer = userUtil.getCustomer();
        if (customer != null) {
            queryWrapper.eq("customer_id", customer.getId());
        }
        queryWrapper.eq("shipping_status", "5");//已签收运单
        queryWrapper.isNull("evaluation_id");
        Page<HyShippingNote> page = new Page<HyShippingNote>(pageNo, pageSize);
        IPage<HyShippingNote> pageList = hyShippingNoteService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    //	@AutoLog(value = "运单表轨迹-分页列表查询")
    @ApiOperation(value = "运单表轨迹-分页列表查询", notes = "运单表轨迹-分页列表查询")
    @GetMapping(value = "/tqlist")
    public Result<?> tqlist(HyShippingNote hyShippingNote,
                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                            HttpServletRequest req) {
        QueryWrapper<HyShippingNote> queryWrapper = QueryGenerator.initQueryWrapper(hyShippingNote, req.getParameterMap());
        List<String> shippingStatus = Arrays.asList(new String[]{"4", "5"});
        queryWrapper.in("shipping_status", shippingStatus);//已签收运单
        Page<HyShippingNote> page = new Page<HyShippingNote>(pageNo, pageSize);
        IPage<HyShippingNote> pageList = hyShippingNoteService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    /**
     * 编辑
     *
     * @param hyShippingNote
     * @return
     */
    @AutoLog(value = "运单表-编辑")
    @ApiOperation(value = "运单表-编辑", notes = "运单表-编辑")
    @PutMapping(value = "/edit")
    @RequiresPermissions("shipping:edit")
    @Transactional
    public Result<?> edit(@RequestBody HyShippingNoteVO hyShippingNote) {
        HyShippingNote old = hyShippingNoteService.getById(hyShippingNote.getId());
        if (old == null) {
            return Result.error("数据不存在!");
        }
        String shippingPayStatus = old.getShippingPayStatus();
        if ("5".equals(shippingPayStatus)) {
            return Result.error("已申请支付,不能修改");
        }
        /*if ("6".equals(shippingPayStatus)) {
            return Result.error("已支付完成,不能修改");
        }*/
        if ("7".equals(shippingPayStatus)) {
            return Result.error("已申请支付,不能修改");
        }

        //Added start at 2024-04-11 for 防止多人操作数据没刷新后，覆盖状态
        if (!old.getShippingStatus().equals(hyShippingNote.getShippingStatus())
                || !old.getShippingPayStatus().equals(hyShippingNote.getShippingPayStatus())) {
            return Result.error("该运单数据已更新，请刷新后操作");
        }

        if (hyShippingNote.getStatusDtLoading() != null && hyShippingNote.getStatusDtUnloading() != null) {
            Integer second = DateUtils.getDifferentDaysByMillisecond(hyShippingNote.getStatusDtLoading(), hyShippingNote.getStatusDtUnloading());
            if (second <= 10 * 60) {
                return Result.error("发货和收货时间逻辑有误（订单时间过短）！");
            }
        }
        if (hyShippingNote.getStatusDtReceive() != null && hyShippingNote.getStatusDtLoading() != null) {
            if (hyShippingNote.getStatusDtLoading().before(hyShippingNote.getStatusDtReceive())) {
                throw new JeecgBootException("发货时间应该在接单时间之后,请重新填写!");
            }
        }
        HyCustomer customer = null;
        if (userUtil.isSys()) {
            //管理员如果修改了所属货主,需修改运单分公司为货主签约的分公司
            if (!StringUtils.equals(hyShippingNote.getCustomerId(), old.getCustomerId())) {
                HyCustomerCompany customerCompany = userUtil.getCustomerCompany(hyShippingNote.getCustomerId());
                hyShippingNote.setCompanyId(customerCompany.getCompanyId());//设置公司id
            }
            customer = userUtil.getCustomerById(hyShippingNote.getCustomerId());
        } else {
            customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            String orderMode = hyShippingNote.getOrderMode();
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                        ) {
                    log.error("运单编辑数据错误 {} - {} - {}", hyShippingNote.getAgentId(), hyShippingNote.getCustomerId(), customer.getId());
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                    log.error("运单编辑数据错误 {} - {}", hyShippingNote.getCustomerId(), customer.getId());
                    return Result.error("数据错误!");
                }
            }
        }
        String shippingType = hyShippingNote.getShippingType();
        HyStatusCheckUtil.checkShippingType(shippingType);

        //处理收发货
        List<HyShippingNoteSendAddress> sendAddressList = hyShippingNote.getHyShippingNoteSendAddressList();
        if (sendAddressList == null) {
            return Result.error("未添加发货地址");
        }
        if (sendAddressList.size() == 0) {
            return Result.error("未添加发货地址");
        }
        int sendDestNums = 0;
        HyShippingNoteSendAddress hyShippingNoteSendAddressDest = null;
        for (HyShippingNoteSendAddress item : sendAddressList) {
            if (StringUtils.isEmpty(item.getSendAddress())) {
                return Result.error("发货地址不能为空");
            }
            BigDecimal lat = item.getSendLatitude();
            BigDecimal lng = item.getSendLongitude();
            //如果是导入的运单不再校验收发货经纬度
            if (StrUtil.isEmpty(old.getImportFlag()) || !old.getImportFlag().equals("1")) {
                if (lat == null || lng == null) {
                    return Result.error("发货地址经纬度不能为空");
                }
            }

            if (item.isIzDest()) {
                hyShippingNoteSendAddressDest = item;
                sendDestNums++;
            }
        }
        if (sendDestNums == 0) {
            return Result.error("发货地址未添加始发地");
        }
        if (sendDestNums > 1) {
            return Result.error("发货地址不能有多个始发地");
        }

        hyShippingNote.setAddressSendId(hyShippingNoteSendAddressDest.getAddressSendId());
        hyShippingNote.setSendDate(hyShippingNoteSendAddressDest.getSendDate());
        hyShippingNote.setSendAddressName(hyShippingNoteSendAddressDest.getSendAddressName());
        hyShippingNote.setSendLongitude(hyShippingNoteSendAddressDest.getSendLongitude());
        hyShippingNote.setSendLatitude(hyShippingNoteSendAddressDest.getSendLatitude());
        hyShippingNote.setSendAddress(hyShippingNoteSendAddressDest.getSendAddress());
        hyShippingNote.setSendAreaCode(hyShippingNoteSendAddressDest.getSendAreaCode());
        hyShippingNote.setSendContactName(hyShippingNoteSendAddressDest.getSendContactName());
        hyShippingNote.setSendContactTel(hyShippingNoteSendAddressDest.getSendContactTel());


        //收货地址
        List<HyShippingNoteReceiveAddress> receiveAddressList = hyShippingNote.getHyShippingNoteReceiveAddressList();
        if (receiveAddressList == null) {
            return Result.error("未添加收货地址");
        }
        if (receiveAddressList.size() == 0) {
            return Result.error("未添加收货地址");
        }
        int receiveDestNums = 0;
        HyShippingNoteReceiveAddress hyShippingNoteReceiveAddressDest = null;
        for (HyShippingNoteReceiveAddress item : receiveAddressList) {
            if (StringUtils.isEmpty(item.getReceiveAddress())) {
                return Result.error("收货地址不能为空");
            }
            BigDecimal lat = item.getReceiveLatitude();
            BigDecimal lng = item.getReceiveLongitude();
            //如果是导入的运单不再校验收发货经纬度
            if (StrUtil.isEmpty(old.getImportFlag()) || !old.getImportFlag().equals("1")) {
                if (lat == null || lng == null) {
                    return Result.error("收货地址经纬度不能为空");
                }
            }
            if (item.isIzDest()) {
                hyShippingNoteReceiveAddressDest = item;
                receiveDestNums++;
            }
        }
        if (receiveDestNums == 0) {
            return Result.error("收货地址未添加目的地");
        }
        if (receiveDestNums > 1) {
            return Result.error("收货地址不能有多个目的地");
        }

        hyShippingNote.setAddressSendId(hyShippingNoteReceiveAddressDest.getAddressReceiveId());
        hyShippingNote.setReceiveDate(hyShippingNoteReceiveAddressDest.getReceiveDate());
        hyShippingNote.setReceiveAddressName(hyShippingNoteReceiveAddressDest.getReceiveAddressName());
        hyShippingNote.setReceiveLongitude(hyShippingNoteReceiveAddressDest.getReceiveLongitude());
        hyShippingNote.setReceiveLatitude(hyShippingNoteReceiveAddressDest.getReceiveLatitude());
        hyShippingNote.setReceiveAddress(hyShippingNoteReceiveAddressDest.getReceiveAddress());
        hyShippingNote.setReceiveAreaCode(hyShippingNoteReceiveAddressDest.getReceiveAreaCode());
        hyShippingNote.setReceiveContactName(hyShippingNoteReceiveAddressDest.getReceiveContactName());
        hyShippingNote.setReceiveContactTel(hyShippingNoteReceiveAddressDest.getReceiveContactTel());

        String payType = hyShippingNote.getPayType();
        if (!"2".equals(payType)) {
            hyShippingNote.setCarrierId("");
        }
        if (!"3".equals(payType)) {
            hyShippingNote.setPreFee(BigDecimal.ZERO);
        }

        //当变更油气或者油气金额时，检查油气是否已充值完成，如果充值完成，不能变更油气费
        if ("0".equals(hyShippingNote.getIzUsedGas())) {
            if (!"0".equals(old.getIzUsedGas())) {
                HyShippingNoteGas shippingNoteGas = hyShippingNoteGasService.getByShippingId(hyShippingNote.getId());
                if (hyShippingNoteGasService.checkRecharge(shippingNoteGas)) {
                    return Result.error("油气已充值,请先回收油气");
                }
            }
            hyShippingNote.setGasRechargeAmount(BigDecimal.ZERO);
        } else {
            BigDecimal gasRechargeAmount = hyShippingNote.getGasRechargeAmount();
            if (gasRechargeAmount == null) {
                return Result.error("油气充值金额错误");
            }
            String oldIzUsedGas = old.getIzUsedGas();
            if (!"0".equals(oldIzUsedGas)) {
                BigDecimal oldGasRechargeAmount = old.getGasRechargeAmount();
                if (oldGasRechargeAmount == null) {
                    oldGasRechargeAmount = BigDecimal.ZERO;
                }
                if (gasRechargeAmount.compareTo(oldGasRechargeAmount) != 0) {
                    //当变更油气或者油气金额时，检查油气是否已充值完成，如果充值完成，不能变更油气费
                    HyShippingNoteGas shippingNoteGas = hyShippingNoteGasService.getByShippingId(hyShippingNote.getId());
                    if (hyShippingNoteGasService.checkRecharge(shippingNoteGas)) {
                        return Result.error("油气已充值,不能变更油气费");
                    }
                }
            }
        }

        HyShippingNote shippingNoteNew = new HyShippingNote();
        hyShippingNote.setCreateTime(hyShippingNote.getStatusDtReceive());
        BeanUtils.copyProperties(hyShippingNote, shippingNoteNew);

        String orderMode = shippingNoteNew.getOrderMode();
        if ("3".equals(orderMode)) {

            BigDecimal agentPrice = shippingNoteNew.getAgentPrice();
            if (agentPrice == null) {
                return Result.error("经纪人运费不能为空");
            }
            BigDecimal shippingUnitPrice = shippingNoteNew.getShippingUnitPrice();
            if (shippingUnitPrice == null) {
                return Result.error("司机运费不能为空");
            }
        } else {
            shippingNoteNew.setAgentId("");
            shippingNoteNew.setAgentPrice(BigDecimal.ZERO);
        }

        try {
            int s = Integer.parseInt(shippingPayStatus);
            if (s > 1) {
                //业务审核是否开启
                if (HyCfgUtil.isUsed2("isOpenYewu")) {
                    hyShippingNote.setShippingPayStatus("9"); //业务审核
                } else {
                    hyShippingNote.setShippingPayStatus("1"); //申请对账
                }
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }

        //Modified at 2023-11-08 for 结算吨位在编辑时要判断是否已经存在 装/卸货量，否则会空指针
        if (ObjectUtil.isNotEmpty(shippingNoteNew.getGoodsWeightLoading()) && ObjectUtil.isNotEmpty(shippingNoteNew.getGoodsWeightUnloading())) {
            if (shippingNoteNew.getIzDriverPayset().equals("1")) {
                shippingNoteNew.setSettlementTon(shippingNoteNew.getGoodsWeightLoading());
            } else if (shippingNoteNew.getIzDriverPayset().equals("2")) {
                shippingNoteNew.setSettlementTon(shippingNoteNew.getGoodsWeightUnloading());
            } else if (shippingNoteNew.getIzDriverPayset().equals("0")) {
                if (shippingNoteNew.getGoodsWeightLoading().compareTo(shippingNoteNew.getGoodsWeightUnloading()) < 0) {
                    shippingNoteNew.setSettlementTon(shippingNoteNew.getGoodsWeightLoading());
                } else {
                    shippingNoteNew.setSettlementTon(shippingNoteNew.getGoodsWeightUnloading());
                }
            }
        }

        hyShippingNoteService.ModifyFreightRiskControl(old, shippingNoteNew);

        hyShippingNoteService.updateById(shippingNoteNew);

        hyShippingNoteSendAddressService.deleteByShippingId(hyShippingNote.getId());
        for (HyShippingNoteSendAddress item : sendAddressList) {
            item.setOrderId(shippingNoteNew.getId());
            item.setCustomerId(shippingNoteNew.getCustomerId());
            item.setShippingId(shippingNoteNew.getId());
        }
        hyShippingNoteSendAddressService.saveBatch(sendAddressList);

        hyShippingNoteReceiveAddressService.deleteByShippingId(hyShippingNote.getId());
        for (HyShippingNoteReceiveAddress item : receiveAddressList) {
            item.setOrderId(shippingNoteNew.getId());
            item.setCustomerId(shippingNoteNew.getCustomerId());
            item.setShippingId(shippingNoteNew.getId());
        }
        hyShippingNoteReceiveAddressService.saveBatch(receiveAddressList);

        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "运单表-编辑")
    @ApiOperation(value = "运单表-编辑", notes = "运单表-编辑")
    @PutMapping(value = "/edit2")
    @RequiresPermissions("shipping:edit")
    public Result<?> edit2(@RequestBody HyShippingNote hyShippingNote) {
        HyShippingNote old = hyShippingNoteService.getById(hyShippingNote.getId());
        if (old == null) {
            return Result.error("数据不存在!");
        }
        String shippingStatus = old.getShippingStatus();
        // TODO: 2023-05-26  税务上传运单有问题,可以修改
        /*if (!"1".equals(shippingStatus) && !"3".equals(shippingStatus) && !"4".equals(shippingStatus)) {
            return Result.error("不能修改!");
        }*/
        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            String orderMode = hyShippingNote.getOrderMode();
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                        ) {
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                    return Result.error("数据错误!");
                }
            }
        }

        BigDecimal goodsWeightLoading = hyShippingNote.getGoodsWeightLoading();
        BigDecimal goodsWeightUnloading = hyShippingNote.getGoodsWeightUnloading();
        if (goodsWeightLoading != null && goodsWeightLoading.compareTo(BigDecimal.ZERO) <= 0) {
            return Result.error("装货量错误!");
        }
        if (goodsWeightUnloading != null && goodsWeightUnloading.compareTo(BigDecimal.ZERO) <= 0) {
            return Result.error("卸货量错误!");
        }
        String imgLoading = hyShippingNote.getImgLoading();
        String imgUnloading = hyShippingNote.getImgUnloading();

//		if("1".equals(settingService.getSettingValueByTag2("usedLoadingImg"))) {
//			if (StringUtils.isEmpty(imgLoading)) {
//				return Result.error("装货凭证不能为空!");
//			}
//		}
//		if("1".equals(settingService.getSettingValueByTag2("usedUnLoadingImg"))) {
//			if (StringUtils.isEmpty(imgUnloading)) {
//				return Result.error("卸货凭证不能为空!");
//			}
//		}

        if (hyShippingNote.getStatusDtLoading() != null && hyShippingNote.getStatusDtUnloading() != null) {
            Integer second = DateUtils.getDifferentDaysByMillisecond(hyShippingNote.getStatusDtLoading(), hyShippingNote.getStatusDtUnloading());
            if (second <= 10 * 60) {
                return Result.error("发货和收货时间逻辑有误（订单时间过短）！");
            }
        }

        if (hyShippingNote.getStatusDtReceive() != null && hyShippingNote.getStatusDtLoading() != null) {
            if (hyShippingNote.getStatusDtLoading().before(hyShippingNote.getStatusDtReceive())) {
                throw new JeecgBootException("发货时间应该在接单时间之后,请重新填写!");
            }
        }

        String loadingSceneImg = hyShippingNote.getLoadingSceneImg();
        String unloadingSceneImg = hyShippingNote.getUnloadingSceneImg();

        HyCompanyConfig companyConfig = companyConfigService.getByCompanyId(old.getCompanyId());
        if (companyConfig != null && 1 == companyConfig.getScenePhoto()) {
            //是否修改装卸货现场图片 ，如修改重新添加水印。
            if (StringUtils.isNotEmpty(loadingSceneImg)) {
                if (!StringUtils.equals(loadingSceneImg, old.getLoadingSceneImg())) {
                    String waterMarkImg = hyShippingNoteService.buildWaterMarkImg(old, loadingSceneImg, "send");
                    old.setLoadingSceneImg(StringUtils.isNotEmpty(waterMarkImg) ? waterMarkImg : loadingSceneImg);
                }
            }
            if (StringUtils.isNotEmpty(unloadingSceneImg)) {
                if (!StringUtils.equals(unloadingSceneImg, old.getUnloadingSceneImg())) {
                    String waterMarkImg = hyShippingNoteService.buildWaterMarkImg(old, unloadingSceneImg, "receive");
                    old.setUnloadingSceneImg(StringUtils.isNotEmpty(waterMarkImg) ? waterMarkImg : unloadingSceneImg);
                }
            }
        } else {
            old.setLoadingSceneImg(loadingSceneImg);
            old.setUnloadingSceneImg(unloadingSceneImg);
        }
        old.setGoodsWeightLoading(goodsWeightLoading);
        old.setGoodsWeightUnloading(goodsWeightUnloading);

        if (StringUtils.isEmpty(imgLoading)) {
            old.setImgLoading("");
        }
        if (StringUtils.isEmpty(imgUnloading)) {
            old.setImgUnloading("");
        }
        old.setStatusDtLoading(hyShippingNote.getStatusDtLoading());
        old.setStatusDtReceive(hyShippingNote.getStatusDtReceive());
        old.setCreateTime(hyShippingNote.getStatusDtReceive());
        old.setStatusDtUnloading(hyShippingNote.getStatusDtUnloading());
        old.setInformationFee(hyShippingNote.getInformationFee());
        old.setUnloadingFee(hyShippingNote.getUnloadingFee());
        old.setPenalty(hyShippingNote.getPenalty());
        old.setPenaltyReason(hyShippingNote.getPenaltyReason());

        old.setBz(hyShippingNote.getBz());
        old.setUnloadingBz(hyShippingNote.getUnloadingBz());
        old.setExamineRemark(hyShippingNote.getExamineRemark());

        if (StringUtils.isNotEmpty(hyShippingNote.getPaymentCertificateImg())) {
            old.setPaymentCertificateImg(hyShippingNote.getPaymentCertificateImg());
        }

        //装卸货榜单加水印
        hyShippingNoteService.getWatermarkPic(old, imgLoading, imgUnloading,
                old.getImgLoading(), old.getImgUnloading()
        );

        //Modified at 2023-11-08 for 结算吨位在编辑时要判断是否已经存在 装/卸货量，否则会空指针
        if (ObjectUtil.isNotEmpty(old.getGoodsWeightLoading()) && ObjectUtil.isNotEmpty(old.getGoodsWeightUnloading())) {
            if (old.getIzDriverPayset().equals("1")) {
                old.setSettlementTon(old.getGoodsWeightLoading());
            } else if (old.getIzDriverPayset().equals("2")) {
                old.setSettlementTon(old.getGoodsWeightUnloading());
            } else if (old.getIzDriverPayset().equals("0")) {
                if (old.getGoodsWeightLoading().compareTo(old.getGoodsWeightUnloading()) < 0) {
                    old.setSettlementTon(old.getGoodsWeightLoading());
                } else {
                    old.setSettlementTon(old.getGoodsWeightUnloading());
                }
            }
        }

        hyShippingNoteService.updateById(old);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "运单表-通过id删除")
    @ApiOperation(value = "运单表-通过id删除", notes = "运单表-通过id删除")
    @DeleteMapping(value = "/delete")
    @Transactional
//	@RequiresPermissions("shipping:delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {

        HyShippingNote hyShippingNote = hyShippingNoteService.getById(id);
        if (hyShippingNote == null) {
            return Result.error("数据不存在!");
        }
        String shippingPayStatus = hyShippingNote.getShippingPayStatus();
        if ("5".equals(shippingPayStatus)) {
            return Result.error("已申请支付,不能删除");
        }
        if ("6".equals(shippingPayStatus)) {
            return Result.error("已支付完成,不能删除");
        }
        if ("7".equals(shippingPayStatus)) {
            return Result.error("已申请支付,不能删除");
        }

        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            String orderMode = hyShippingNote.getOrderMode();
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                        ) {
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                    return Result.error("数据错误!");
                }
            }
        }

//        //如果绑定了智运宝设备要终止围栏
//        if (StrUtil.isNotEmpty(hyShippingNote.getVehicleDevice())) {
//            this.zybService.cancelShippingFence(hyShippingNote.getShippingNoteNumber());
//        }

        //检查并删除支付订单
        hyBillService.deleteBillListByShippNoteId(id);
        hyShippingNoteService.removeById(id);
        return Result.OK("删除成功!");
    }

//	@AutoLog(value = "运单表-批量删除")
//	@ApiOperation(value="运单表-批量删除", notes="运单表-批量删除")
//	@DeleteMapping(value = "/deleteBatch")
//	@RequiresPermissions("shipping:deleteBatch")
//	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//		this.hyShippingNoteService.removeByIds(Arrays.asList(ids.split(",")));
//		return Result.OK("批量删除成功!");
//	}

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "运单表-通过id查询", notes = "运单表-通过id查询")
    @GetMapping(value = "/queryById")
    @EntityDict
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getById(id);
        if (hyShippingNote == null) {
            return Result.error("未找到对应数据");
        }
        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("无查看权限");
            }
            String orderMode = hyShippingNote.getOrderMode();
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                        ) {
                    return Result.error("无查看权限!");
                }
            } else {
                if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                    return Result.error("无查看权限!");
                }
            }
        }
        return Result.OK(hyShippingNote);
    }

    @RequestMapping(value = "/exportXls")
    @RequiresPermissions("shipping:exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HyShippingNoteDTO shippingNoteDTO) {
        QueryWrapper<HyShippingNoteDTO> queryWrapper = new QueryWrapper();
        String shippingPayStatus = shippingNoteDTO.getShippingPayStatus();
        HyCustomer customer = null;
        HyCustomerConfig customerConfig = null;

        String role = "";// 1 货主
        if (userUtil.isSys()) {

            if (StringUtils.isNotEmpty(shippingNoteDTO.getCustomerId())) {
                queryWrapper.eq("hy_shipping_note.customer_id", shippingNoteDTO.getCustomerId());
            }
        } else {
            customer = userUtil.getCustomer();
            if (customer == null) {
                throw new JeecgBootException("货主信息不存在!");
            }
            customerConfig = customerConfigService.getByCustomerId(customer.getId());

            role = "1";
            if ("4".equals(shippingPayStatus) || "7".equals(shippingPayStatus)) {
                queryWrapper.eq("hy_shipping_note.customer_id", customer.getId());
            } else {
                HyCustomer finalCustomer = customer;
                queryWrapper.and(
                        qw -> qw.eq("hy_shipping_note.customer_id", finalCustomer.getId())
                                .or()
                                .eq("hy_shipping_note.agent_id", finalCustomer.getId()));
            }
        }

        //如果用货源号模糊搜索，而不是直接用货源ID进行搜索时
        if (StrUtil.isNotEmpty(shippingNoteDTO.getOrderNum()) && StrUtil.isEmpty(shippingNoteDTO.getOrderId())) {
            List<HyOrder> hyOrderList = this.hyOrderService.list(new LambdaQueryWrapper<HyOrder>().like(HyOrder::getOrderNum, shippingNoteDTO.getOrderNum()));
            List<String> orderIds = hyOrderList.stream().map(HyOrder::getId).collect(Collectors.toList());
            queryWrapper.in("hy_shipping_note.order_id", orderIds);
        }

        setQueryWrapper(shippingNoteDTO, queryWrapper);

        queryWrapper.eq("hy_shipping_note.del_flag", "0");

        if ("TJSWYSB".equals(shippingNoteDTO.getExportMark())) {
            if (StringUtils.isNotEmpty(shippingNoteDTO.getUploadStatusType())) {
                queryWrapper.nested(
                        qw -> qw.eq("d.tj_tax_upload_status", "1")
                                .eq("company.tj_tax_upload_status", "1")
                                .eq("hy_shipping_note.tax_upload_status", "1")
                                .eq("customer.tj_tax_upload_status", "1")
                );

            } else {

                queryWrapper.nested(
                        qw -> qw.ne("d.tj_tax_upload_status", "1")
                                .or().ne("company.tj_tax_upload_status", "1")
                                .or().ne("hy_shipping_note.tax_upload_status", "1")
                                .or().ne("customer.tj_tax_upload_status", "1")
                );
            }
            //导出
            if (StringUtils.isNotEmpty(shippingNoteDTO.getPayDt_begin())) {
                queryWrapper.ge("hy_shipping_note.pay_dt", shippingNoteDTO.getPayDt_begin() + " 00:00:00");
            } else {

                Date now1 = new Date();
                int month = now1.getMonth() + 1;
                if (month == 1) {
                    Calendar calendar = new GregorianCalendar();
                    calendar.setTime(now1);
                    calendar.add(Calendar.MONTH, -1);// 把日期往后增加一天.整数往后推,负数往前移动
                    // 获取某月最小天数
                    int firstDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
                    // 设置日历中月份的最小天数
                    calendar.set(Calendar.DAY_OF_MONTH, firstDay);

                    Date endDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
                    String yearStartTime = DateUtils.date2Str(endDate, DateUtils.date_sdf.get()) + " 00:00:00";
                    queryWrapper.ge("hy_shipping_note.pay_dt", yearStartTime);
                } else {
                    Long start = System.currentTimeMillis();
                    String yearStartTime = DateUtils.formatDate1(DateUtils.getYearStartTime(start));
                    queryWrapper.ge("hy_shipping_note.pay_dt", yearStartTime);
                }

            }
        }


        String invoiceId = shippingNoteDTO.getInvoiceId();
        if (StringUtils.isNotEmpty(invoiceId)) {
            queryWrapper.eq("invoice_id", invoiceId);
        }
        queryWrapper.groupBy("hy_shipping_note.shipping_note_number");
        String byDesc = shippingNoteDTO.getByDesc();
        if (StringUtils.isNotEmpty(byDesc)) {
            String[] bys = byDesc.split(",");
            for (String by : bys) {
                queryWrapper.orderByDesc("hy_shipping_note." + by);
            }

        } else {
            queryWrapper.orderByDesc("hy_shipping_note.create_time");
        }

        String selections = request.getParameter("selections");
        if (StringUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("hy_shipping_note.id", selectionList);
        }

        String domianURL = request.getParameter("domianURL");
        if (StringUtils.isNotEmpty(domianURL)) {
            domianURL += "/";
        } else {
            domianURL = "";
        }

        List<HyShippingNoteDTO> list = hyShippingNoteService.getList(queryWrapper);
        for (HyShippingNoteDTO hyShippingNoteDTO : list) {
//			if("3".equals(hyShippingNoteDTO.getPayType())){
//				if(hyShippingNoteDTO.getCostPayTotal() != null && hyShippingNoteDTO.getPreFee() != null) {
//					hyShippingNoteDTO.setCostPayTotal(hyShippingNoteDTO.getCostPayTotal().add(hyShippingNoteDTO.getPreFee()));
//				}
//			}
            hyShippingNoteDTO.setContractUnitPrice(hyShippingNoteDTO.getShippingUnitPrice());
            hyShippingNoteDTO.setCostPayTotal(hyShippingNoteDTO.getCustomerFee());

//            if (hyShippingNoteDTO.getDriverBankId()==null||StringUtils.isEmpty(hyShippingNoteDTO.getDriverBankId())||hyShippingNoteDTO.getDriverBankId().equals("")){
//                //查找司机默认银行卡
//                HyDriverBank defaultDriverBank = hyDriverBankService.getDefaultDriverBank(hyShippingNoteDTO.getDriverId());
//
//                if (defaultDriverBank!=null){
//                    hyShippingNoteDTO.setSjyhkh(defaultDriverBank.getBankNum());
//                    hyShippingNoteDTO.setSjyhmc(defaultDriverBank.getBankType());
//                }
//            }
            //如果运单的司机银行卡与列表的司机银行卡不一致，则需要重新赋值
            String driverBankId = hyShippingNoteService.getById(hyShippingNoteDTO.getId()).getDriverBankId();
            HyDriverBank driverBank = hyDriverBankService.getById(driverBankId);
            if(driverBank!=null&&!driverBank.getBankNum().equals(hyShippingNoteDTO.getSjyhkh())){
                hyShippingNoteDTO.setSjyhmc(driverBank.getBankType());
                hyShippingNoteDTO.setSjyhkh(driverBank.getBankNum());
            }

            String shippingContract = hyShippingNoteDTO.getShippingContract();
            if (StringUtils.isNotEmpty(shippingContract)) {
                hyShippingNoteDTO.setShippingContract(domianURL + shippingContract);
            }
            String imgLoading = hyShippingNoteDTO.getImgLoading();
            if (StringUtils.isNotEmpty(imgLoading)) {
                hyShippingNoteDTO.setImgLoading(domianURL + imgLoading);
            }

            String imgUnloading = hyShippingNoteDTO.getImgUnloading();
            if (StringUtils.isNotEmpty(imgUnloading)) {
                hyShippingNoteDTO.setImgUnloading(domianURL + imgUnloading);
            }

            if ("1".equals(role)) {
                if (customerConfig != null) {
                    if (!"1".equals(customerConfig.getIzShowDrvierFee())) {
                        if (hyShippingNoteDTO.getOrderMode().equals("3")) {
                            hyShippingNoteDTO.setCostService(new BigDecimal(0));
                            hyShippingNoteDTO.setCustomerFee(new BigDecimal(0));
                            hyShippingNoteDTO.setGoodsWeightLoading(new BigDecimal(0));
                            hyShippingNoteDTO.setGoodsWeightUnloading(new BigDecimal(0));
                            hyShippingNoteDTO.setShippingUnitPrice(new BigDecimal(0));
                            hyShippingNoteDTO.setContractUnitPrice(new BigDecimal(0));
                            hyShippingNoteDTO.setCostPay(new BigDecimal(0));
                            hyShippingNoteDTO.setPreUnitFee(new BigDecimal(0));
                            hyShippingNoteDTO.setPreFee(new BigDecimal(0));
                            hyShippingNoteDTO.setCostPayShipping(new BigDecimal(0));
                            hyShippingNoteDTO.setDriverFee(new BigDecimal(0));
                            hyShippingNoteDTO.setCostPayTotal(new BigDecimal(0));
                            hyShippingNoteDTO.setCustomerFee(new BigDecimal(0));
                            hyShippingNoteDTO.setAgentCostPay(new BigDecimal(0));
                            hyShippingNoteDTO.setAgentCostPayShipping(new BigDecimal(0));
                            hyShippingNoteDTO.setGasRechargeAmount(new BigDecimal(0));
                            hyShippingNoteDTO.setCostPay1(new BigDecimal(0));
                            hyShippingNoteDTO.setCostPay2(new BigDecimal(0));

                        }
                    }
                }
            }
        }

        //如果导出的运单中有货主模式的运单，需要导出货主单价
        boolean orderMode = false;
        if (null != list.stream().filter(s -> s.getOrderMode().equals("4")).findAny().orElse(null)) {
            orderMode = true;
        }
        log.info("是否是货主模式导出,{}", orderMode);

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String title = "运单表";
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, HyShippingNoteDTO.class);

        //按选择列导出
        //log.info("数据-> {}", JSONUtil.toJsonStr(list));
        String selCols = request.getParameter("selCols");
        log.info("选择列导出运单-> cols {}", selCols);
        if ("1".equals(selCols)) {
            String field = request.getParameter("field");
            log.info("选择列导出运单-> field {}", field);
            if (StringUtils.isNotEmpty(field)) {
                List<String> fields = Arrays.asList(field.split(","));
                List<String> selectCols = new ArrayList<>();
                for (String s : fields) {
                    if (StringUtils.isNotEmpty(s)) {
                        int idx = s.indexOf("_dictText");
                        if (idx > -1) {
                            s = s.substring(0, idx);
                        }
                        selectCols.add(s);
                    }
                }

                //运输路线导出，条件routeSlot
                if (fields.contains("routeSlot")) {
                    selectCols.add("sendAddressName");
                    selectCols.add("receiveAddressName");
                }

                //收发货区域导出,条件
                if (fields.contains("routeArea")) {
                    selectCols.add("sendAreaCode");
                    selectCols.add("receiveAreaCode");
                }

                if (orderMode) {
                    selectCols.add("customerPrice");
                    selectCols.add("customerUnitPrice");
                }

                mv.addObject(NormalExcelConstants.EXPORT_FIELDS, StringUtils.join(selectCols, ","));
            }
        }

        ExportParams exportParams = new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
        exportParams.setType(ExcelType.XSSF);
        exportParams.setStyle(HyShippingExcelExportImpl.class);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    public static void main(String[] args) {
        Date now1 = new Date();
        int month = now1.getMonth() + 1;
        if (month == 1) {
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(now1);
            calendar.add(Calendar.MONTH, -1);// 把日期往后增加一天.整数往后推,负数往前移动
            // 获取某月最小天数
            int firstDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
            // 设置日历中月份的最小天数
            calendar.set(Calendar.DAY_OF_MONTH, firstDay);

            Date endDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
            String yearStartTime = DateUtils.date2Str(endDate, DateUtils.date_sdf.get()) + " 00:00:00";
            System.out.println(yearStartTime);
//            queryWrapper.ge("hy_shipping_note.pay_dt",yearStartTime);
        } else {
            Long start = System.currentTimeMillis();
            String yearStartTime = DateUtils.formatDate1(DateUtils.getYearStartTime(start));
            System.out.println(yearStartTime);
//            queryWrapper.ge("hy_shipping_note.pay_dt",yearStartTime);
        }
    }

    @RequestMapping(value = "/preExportXls")
    @RequiresPermissions("shipping:exportXls")
    public ModelAndView preExportXls(HttpServletRequest request, HyShippingNoteDTO shippingNoteDTO) {
        QueryWrapper<HyShippingNoteDTO> queryWrapper = new QueryWrapper();
        String shippingPayStatus = shippingNoteDTO.getShippingPayStatus();

        if (userUtil.isSys()) {
            if (StringUtils.isNotEmpty(shippingNoteDTO.getCustomerId())) {
                queryWrapper.eq("hy_shipping_note.customer_id", shippingNoteDTO.getCustomerId());
            }
        } else {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                throw new JeecgBootException("货主信息不存在!");
            }

//			if("4".equals(shippingPayStatus) || "7".equals(shippingPayStatus) ){
//				queryWrapper.eq("hy_shipping_note.customer_id", customer.getId());
//			}else {
//				queryWrapper.and(
//						qw -> qw.eq("hy_shipping_note.customer_id", customer.getId())
//								.or()
//								.eq("hy_shipping_note.agent_id", customer.getId()));
//			}
            queryWrapper.eq("hy_shipping_note.customer_id", customer.getId());
        }
        setQueryWrapper(shippingNoteDTO, queryWrapper);

        queryWrapper.eq("hy_shipping_note.del_flag", "0");

        String invoiceId = shippingNoteDTO.getInvoiceId();
        if (StringUtils.isNotEmpty(invoiceId)) {
            queryWrapper.eq("invoice_id", invoiceId);
        }

        String byDesc = shippingNoteDTO.getByDesc();
        if (StringUtils.isNotEmpty(byDesc)) {
            String[] bys = byDesc.split(",");
            for (String by : bys) {
                queryWrapper.orderByDesc("hy_shipping_note." + by);
            }

        } else {
            queryWrapper.orderByDesc("hy_shipping_note.create_time");
        }
        String selections = request.getParameter("selections");
        if (StringUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("hy_shipping_note.id", selectionList);
        }

        List<HyShippingNoteDTO> list = hyShippingNoteService.getList(queryWrapper);

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String title = "运单表";
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, HyShippingNoteDTO.class);
        //按选择列导出
        String selCols = request.getParameter("selCols");
        if ("1".equals(selCols)) {
            String field = request.getParameter("field");
            if (StringUtils.isNotEmpty(field)) {
                List<String> fields = Arrays.asList(field.split(","));
                List<String> selectCols = new ArrayList<>();
                for (String s : fields) {
                    if (StringUtils.isNotEmpty(s)) {
                        int idx = s.indexOf("_dictText");
                        if (idx > -1) {
                            s = s.substring(0, idx);
                        }
                        selectCols.add(s);
                    }
                }
                mv.addObject(NormalExcelConstants.EXPORT_FIELDS, StringUtils.join(selectCols, ","));
            }
        }
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    @RequestMapping(value = "/exportXls2")
    public ModelAndView exportXls2(HttpServletRequest request, HyShippingNote shippingNote) throws Exception {

        String invoiceId = shippingNote.getInvoiceId();
        if (StringUtils.isEmpty(invoiceId)) {
            throw new Exception("开票信息不能为空");
        }

        HyInvoice invoice = hyInvoiceService.getById(invoiceId);
        if (invoice == null) {
            throw new Exception("开票信息不能为空");
        }

        QueryWrapper<HyShippingNote> queryWrapper = QueryGenerator.initQueryWrapper(shippingNote, request.getParameterMap());
        List<HyShippingNote> list = hyShippingNoteService.list(queryWrapper);

        HyInvoiceDTO add = new HyInvoiceDTO();
        add.setYsf("默认：运输费");
        add.setJldw("默认：吨");
        add.setGgxh("[品名][发货市][发货区]-[卸货市][卸货区][车牌号]");
        add.setInvoiceGoodsWeightStr("结算重量(保留小数点2位)");
        add.setInvoiceAmtStr("价税合计金额(保留小数点2位)");
        add.setInvoiceRateStr("默认0.09");
        add.setInvoiceTaxStr("税额=金额*0.09（保留小数点2位）");
        add.setInvoicePriceStr("单价=金额/数量（保留小数点后6位）");

        add.setJgfs("默认：1");
        add.setSsflbmbb("默认：39.0");
        add.setSsflbm("默认：3010502020200000000");
        add.setYhzc("默认：0");
        add.setZw("默认：0");

        Set<String> setDriverid = new HashSet<>();
        Set<String> setVehicleid = new HashSet<>();
        Set<String> setOrderid = new HashSet<>();
        Set<String> setAreaCode = new HashSet<>();
        for (HyShippingNote hyShippingNote : list) {
            setDriverid.add(hyShippingNote.getDriverId());
            setVehicleid.add(hyShippingNote.getVehicleId());
            setOrderid.add(hyShippingNote.getOrderId());
            setAreaCode.add(hyShippingNote.getSendAreaCode() + "000000");
            setAreaCode.add(hyShippingNote.getReceiveAreaCode() + "000000");
        }
        List<HyVehicle> hyVehicles = hyVehicleService.listByIds(setVehicleid);
        List<HyDriver> hyDrivers = hyDriverService.listByIds(setDriverid);
        List<HyOrder> hyOrders = iHyOrderService.listByIds(setOrderid);
        List<HyArea> areaCodes = hyAreaService.list(new QueryWrapper<HyArea>().in("area_code", setAreaCode));
        Map<String, HyVehicle> mapVehicles = new HashMap<>();
        for (HyVehicle hyVehicle : hyVehicles) {
            mapVehicles.put(hyVehicle.getId(), hyVehicle);
        }
        Map<String, HyDriver> mapDrivers = new HashMap<>();
        for (HyDriver hyDriver : hyDrivers) {
            mapDrivers.put(hyDriver.getId(), hyDriver);
        }
        Map<String, HyOrder> mapOrders = new HashMap<>();
        for (HyOrder hyOrder : hyOrders) {
            mapOrders.put(hyOrder.getId(), hyOrder);
        }

        Map<String, HyArea> mapAreaCodes = new HashMap<>();
        for (HyArea areaCode : areaCodes) {
            mapAreaCodes.put("" + areaCode.getAreaCode(), areaCode);
        }

        List<HyInvoiceDTO> exportList = new ArrayList<>();
        exportList.add(0, add);
        BigDecimal invoiceRate = invoice.getInvoiceRate();
        String invoiceRateStr = invoiceRate + "";
        for (HyShippingNote h : list) {

            HyVehicle vehicle = mapVehicles.get(h.getVehicleId());
            HyDriver driver = mapDrivers.get(h.getDriverId());
            HyOrder order = mapOrders.get(h.getOrderId());
            if (vehicle != null && order != null) {
                HyInvoiceDTO one = new HyInvoiceDTO();

                String scode = h.getSendAreaCode() + "000000";
                HyArea sarea = mapAreaCodes.get(scode);
                String Fcity = "";
                String Fdistrict = "";
                if (sarea != null) {
                    String mergerName = sarea.getMergerName();
                    String[] split = mergerName.split(",");
                    if (split.length >= 3) {
                        Fcity = split[1];
                        Fdistrict = split[2];
                    } else {
                        Fcity = split[0];
                        Fdistrict = split[1];
                    }
                }

                String recode = h.getReceiveAreaCode() + "000000";
                HyArea rarea = mapAreaCodes.get(recode);
                String Scity = "";
                String Sdistrict = "";
                if (rarea != null) {
                    String mergerName = rarea.getMergerName();
                    String[] split = mergerName.split(",");
                    if (split.length >= 3) {
                        Scity = split[1];
                        Sdistrict = split[2];
                    } else {
                        Scity = split[0];
                        Sdistrict = split[1];
                    }
                }

                one.setInvoiceRateStr(invoiceRateStr);
                one.setGgxh(order.getDescriptionOfGoods() + Fcity + Fdistrict + "-" + Scity + Sdistrict + vehicle.getVehicleNumber());
                one.setInvoiceGoodsWeightStr(String.format("%.2f", h.getGoodsWeightUnloading()));
                BigDecimal costPayTotal = h.getCustomerFee();

                one.setInvoiceAmtStr(String.valueOf(costPayTotal));
//				税额=金额/1.09*1.09（保留小数点2位）

                one.setInvoiceTaxStr(String.format("%.2f", costPayTotal.multiply(invoiceRate)));
                //单价=金额/数量
                BigDecimal divide = costPayTotal.divide(h.getGoodsWeightUnloading(), 6, BigDecimal.ROUND_HALF_UP);
                one.setInvoicePriceStr(String.valueOf(divide));
                one.setSjdh(driver.getTelephone());
                one.setSjsfzh(driver.getIdcard());
                exportList.add(one);
            }

        }


        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "开票清单"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, HyInvoiceDTO.class);
        ExportParams exportParams = new ExportParams();
        exportParams.setAddIndex(true);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }


    @RequestMapping(value = "/exportXls3")
    public ModelAndView exportXls3(HttpServletRequest request, HyShippingNote shippingNote) throws Exception {

        String invoiceId = shippingNote.getInvoiceId();
        if (StringUtils.isEmpty(invoiceId)) {
            throw new Exception("开票信息不能为空");
        }

        HyInvoice invoice = hyInvoiceService.getById(invoiceId);
        if (invoice == null) {
            throw new Exception("开票信息不能为空");
        }

        QueryWrapper<HyShippingNote> queryWrapper = QueryGenerator.initQueryWrapper(shippingNote, request.getParameterMap());
        List<HyShippingNote> list = hyShippingNoteService.list(queryWrapper);

//		Set<String> setAreaCode = new HashSet<>();
//		for (HyShippingNote hyShippingNote : list) {
//			setAreaCode.add(hyShippingNote.getSendAreaCode() + "000000");
//			setAreaCode.add(hyShippingNote.getReceiveAreaCode() + "000000");
//		}

//		List<HyArea> areaCodes = hyAreaService.list(new QueryWrapper<HyArea>().in("area_code", setAreaCode));
//
//		Map<String,HyArea> mapAreaCodes = new HashMap<>();
//		for (HyArea areaCode : areaCodes) {
//			mapAreaCodes.put( "" + areaCode.getAreaCode() , areaCode);
//		}

        List<HyInvoiceDTO3> exportList = new ArrayList<>();
        BigDecimal invoiceRate = new BigDecimal("0.09");
        BigDecimal divideInvoiceRate = new BigDecimal("1.09");
        //开票数量类型(1装货量2卸货量)
        String invoiceWeightType = invoice.getInvoiceWeightType();
        for (HyShippingNote h : list) {
            HyInvoiceDTO3 one = new HyInvoiceDTO3();
            one.setGoodsUnit(h.getGoodsUnit());
            //车牌号
            one.setGgxh(h.getVehicleId());
            BigDecimal sl = null;
            if ("1".equals(invoiceWeightType)) {
                sl = h.getGoodsWeightLoading();
            } else if ("2".equals(invoiceWeightType)) {
                sl = h.getGoodsWeightUnloading();
            } else {
                sl = (h.getGoodsWeightLoading().compareTo(h.getGoodsWeightUnloading()) > 0 ? h.getGoodsWeightUnloading() : h.getGoodsWeightLoading());
            }
            one.setSl(sl);
            BigDecimal costPayTotal = h.getCustomerFee();

            one.setCostPayTotal(costPayTotal);
            one.setInvoiceRate(invoiceRate);
            //税额=金额/1.09*0.09（保留小数点2位）
            BigDecimal se = costPayTotal.divide(divideInvoiceRate, 9, BigDecimal.ROUND_HALF_UP).multiply(invoiceRate).setScale(2, BigDecimal.ROUND_HALF_UP);
            one.setInvoiceTax(se);
            one.setSsflbm("3010502020200000000");
            one.setQyspbm("10400003");

            //单价
            if (!"dockerprod".equals(activeProfile)) {
                BigDecimal danjia = costPayTotal.divide(sl, 12, BigDecimal.ROUND_HALF_UP);
                one.setInvoicePrice(danjia.toPlainString());
            }

//			one.setSendAddressName(h.getSendAddressName());
//			one.setReceiveAddressName(h.getReceiveAddressName());
            exportList.add(one);
        }


        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "开票清单"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, HyInvoiceDTO3.class);
        ExportParams exportParams = new ExportParams();
        exportParams.setAddIndex(true);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/importShippingNote", method = RequestMethod.POST)
    @RequiresPermissions("shipping:importExcel")
    public Result<?> importExcelShippingNote(HttpServletRequest request) throws InterruptedException {
        List<ImportShippingNoteDTO> list = ExcelUtil.importExcel(request, ImportShippingNoteDTO.class);

        log.info("开始导入运单,总行数{}", list.size());
        if (CollectionUtils.isEmpty(list)) {
            return Result.error("导入数据不能为空！");
        }
        this.checkData(list);

        List<ImportShippingNoteDTO> importShippingNoteDTOS = hyShippingNoteService.queryImportShippingNoteDTOS(list);

        List<HyShippingNote> shippingNotes = new ArrayList<>();
        for (int j = 0; j < importShippingNoteDTOS.size(); j++) {
            ImportShippingNoteDTO importShippingNoteDTO = importShippingNoteDTOS.get(j);
            int intIndex = j + 2;
            HyShippingNote shippingNote = hyShippingNoteService.ImportShippingNoteDTOTOShippingNote(importShippingNoteDTO, String.valueOf(intIndex));
            shippingNotes.add(shippingNote);
        }

        hyShippingNoteService.saveBatchShippingNote(shippingNotes);
        return Result.OK("文件导入成功！数据行数：" + shippingNotes.size());
    }


    private void checkData(List<ImportShippingNoteDTO> list) {
        int i = 2;
        for (ImportShippingNoteDTO importShippingNoteDTO : list) {
            String key = String.valueOf(i);
            if (StringUtils.isBlank(importShippingNoteDTO.getCompanyName())) {
                throw new JeecgBootException("第" + key + "行  公司信息不能为空,请先补充信息");
            }
            if (StringUtils.isBlank(importShippingNoteDTO.getCustomerName())) {
                throw new JeecgBootException("第" + key + "行  货主信息不能为空,请先补充信息");
            }
            if (StringUtils.isBlank(importShippingNoteDTO.getOrderNum())) {
                throw new JeecgBootException("第" + key + "行  货源信息不能为空,请先补充信息");
            }
            if (StringUtils.isBlank(importShippingNoteDTO.getDriverName())) {
                throw new JeecgBootException("第" + key + "行  司机信息不能为空,请先补充信息");
            }
            if (StringUtils.isBlank(importShippingNoteDTO.getTelephone())) {
                throw new JeecgBootException("第" + key + "行 司机手机号不能为空,请先补充信息");
            }

            if (StringUtils.isBlank(importShippingNoteDTO.getVehicleNumber())) {
                throw new JeecgBootException("第" + key + "行  车辆信息不能为空,请先补充信息");
            }

            if (importShippingNoteDTO.getGoodsWeightLoading() == null ||
                    importShippingNoteDTO.getGoodsWeightLoading().compareTo(BigDecimal.ZERO) == 0) {
                throw new JeecgBootException("第" + key + "行实际装载量不能为空");
            }
            if (importShippingNoteDTO.getGoodsWeightUnloading() == null ||
                    importShippingNoteDTO.getGoodsWeightUnloading().compareTo(BigDecimal.ZERO) == 0) {
                throw new JeecgBootException("第" + key + "行实际卸货量不能为空");
            }
            if (importShippingNoteDTO.getShippingUnitPrice() == null ||
                    importShippingNoteDTO.getShippingUnitPrice().compareTo(BigDecimal.ZERO) == 0) {
                throw new JeecgBootException("第" + key + "行运费单价(收入)不能为空");
            }
            if (importShippingNoteDTO.getCostPayShipping() == null ||
                    importShippingNoteDTO.getCostPayShipping().compareTo(BigDecimal.ZERO) == 0) {
                throw new JeecgBootException("第" + key + "行实付金额不能为空");
            }
            if (importShippingNoteDTO.getCostPay() == null ||
                    importShippingNoteDTO.getCostPay().compareTo(BigDecimal.ZERO) == 0) {
                throw new JeecgBootException("第" + key + "行应付金额不能为空");
            }

            if (StringUtils.isBlank(importShippingNoteDTO.getStatusDtReceive())) {
                throw new JeecgBootException("第" + key + "行实际接单时间不能为空");
            }
            if (StringUtils.isBlank(importShippingNoteDTO.getStatusDtLoading())) {
                throw new JeecgBootException("第" + key + "行实际发货时间不能为空");
            }
            if (StringUtils.isBlank(importShippingNoteDTO.getStatusDtUnloading())) {
                throw new JeecgBootException("第" + key + "行实际收货时间不能为空");
            }
            if (StringUtils.isBlank(importShippingNoteDTO.getStatusDtSign())) {
                throw new JeecgBootException("第" + key + "行实际签收时间不能为空");
            }
            if ("6".equals(importShippingNoteDTO.getShippingPayStatus()) && StringUtils.isBlank(importShippingNoteDTO.getPayDt())) {
                throw new JeecgBootException("第" + key + "行运费支付时间不能为空");
            }
            if (StringUtils.isBlank(importShippingNoteDTO.getCreateTime())) {
                throw new JeecgBootException("第" + key + "行创建时间不能为空");
            }
            Date createTime = DateUtils.stringToDateTime(importShippingNoteDTO.getCreateTime());

            Date statusDtSign = DateUtils.stringToDateTime(importShippingNoteDTO.getStatusDtSign());

            Date statusDtUnloading = DateUtils.stringToDateTime(importShippingNoteDTO.getStatusDtUnloading());

            Date statusDtLoading = DateUtils.stringToDateTime(importShippingNoteDTO.getStatusDtLoading());

            Date statusDtReceive = DateUtils.stringToDateTime(importShippingNoteDTO.getStatusDtReceive());

            if (statusDtReceive == null) {
                throw new JeecgBootException("第" + key + "行实际接单时间不正确,应为日期时间文本格式");
            }

            if (statusDtLoading == null) {
                throw new JeecgBootException("第" + key + "行实际发货时间不正确,应为日期时间文本格式");
            }

            if (statusDtUnloading == null) {
                throw new JeecgBootException("第" + key + "行实际收货时间不正确,应为日期时间文本格式");
            }

            if (statusDtSign == null) {
                throw new JeecgBootException("第" + key + "行实际签收时间不正确,应为日期时间文本格式");
            }
            if (createTime == null) {
                throw new JeecgBootException("第" + key + "行创建时间不正确,应为日期时间文本格式");
            }

            if (StringUtils.isBlank(importShippingNoteDTO.getShippingStatus())) {
                throw new JeecgBootException("第" + key + "行运单状态不能为空");
            }

            if (StringUtils.isBlank(importShippingNoteDTO.getShippingPayStatus())) {
                throw new JeecgBootException("第" + key + "行支付状态不能为空");
            }

            if ("6".equals(importShippingNoteDTO.getShippingPayStatus()) && StringUtils.isNotBlank(importShippingNoteDTO.getPayDt())) {
                Date payDt = DateUtils.stringToDateTime(importShippingNoteDTO.getPayDt());
                if (payDt == null) {
                    throw new JeecgBootException("第" + key + "行运费支付时间不正确,应为日期时间文本格式");
                }
            }

// Delete start at 2023-10-13 for 这个运单导入地址没什么用，实际上还是关联到货源后取的货源收发货地址
//            if (StringUtils.isBlank(importShippingNoteDTO.getSendAddress())) {
//                throw new JeecgBootException("第" + key + "行发货详细地址不能为空");
//            }
//
//            if (StringUtils.isBlank(importShippingNoteDTO.getReceiveAddress())) {
//                throw new JeecgBootException("第" + key + "行收货详细地址不能为空");
//            }
// Delete end at 2023-10-13

            i++;
        }


    }


    /**
     * 通过excel批量修改运单数据
     *
     * @param request
     * @return
     */
    @AutoLog("通过excel批量修改运单数据")
    @RequestMapping(value = "/importUpdateShippingNote", method = RequestMethod.POST)
    public Result<?> importUpdateShippingNote(HttpServletRequest request) {
        List<ImportUpdateShippingNoteDTO> list = ExcelUtil.importExcel(request, ImportUpdateShippingNoteDTO.class);

        log.info("开始导入运单,总行数{}, 数据{}", list.size(), JSONUtil.toJsonStr(list));
        if (CollectionUtils.isEmpty(list)) {
            return Result.error("导入数据不能为空！");
        }

        return hyShippingNoteService.importUpdateShippingNote(list);
    }

    //endregion

    //region 派单
    @AutoLog(value = "运单表-智运宝派单")
    @ApiOperation(value = "运单表-智运宝派单", notes = "运单表-智运宝派单")
    @PutMapping(value = "/zybpaidan")
    public Result<?> zybpaidan(@RequestBody ZybShippingNoteVO zybVO) {
        //合法性判断
        if (StrUtil.isEmpty(zybVO.getOrderId())) {
            return Result.error("货源参数错误");
        }

        if (StrUtil.isEmpty(zybVO.getVehicleId())
                || StrUtil.isEmpty(zybVO.getVehicleDevice())) {
            return Result.error("车辆参数错误");
        }

        return this.hyShippingNoteService.zybpaidan(zybVO);
    }


    @AutoLog(value = "信息补全-智运宝派单")
    @ApiOperation(value = "信息补全-智运宝派单", notes = "信息补全-智运宝派单")
    @PostMapping(value = "/zybComplete")
    public Result<?> zybComplete(@RequestBody ZybShippingNoteVO zybVO) {
        //合法性判断
        if (StrUtil.isEmpty(zybVO.getShippingId())) {
            return Result.error("运单参数错误");
        }

        if (StrUtil.isEmpty(zybVO.getDriverId())) {
            return Result.error("司机参数错误");
        }

        if (StrUtil.isEmpty(zybVO.getCostPayShipping())) {
            return Result.error("运费参数错误");
        }

        return this.hyShippingNoteService.zybComplete(zybVO);
    }


    @AutoLog(value = "手工终止电子围栏")
    @ApiOperation(value = "手工终止电子围栏", notes = "手工终止电子围栏")
    @PostMapping(value = "/zybStop")
    public Result<?> zybStop(@RequestBody ZybShippingNoteVO zybVO) {
        log.info("手工终止电子围栏, {}", JSONUtil.toJsonStr(zybVO));
        if (StrUtil.isEmpty(zybVO.getShippingId())) {
            return Result.error("运单参数错误");
        }

        HyShippingNote hyShippingNote = this.hyShippingNoteService.getById(zybVO.getShippingId());
        if (null == hyShippingNote) {
            return Result.error("运单信息不存在");
        }

        Result result = this.zybService.cancelShippingFence(hyShippingNote.getShippingNoteNumber());
        if (result.getCode().equals(CommonConstant.SC_OK_200)) {
            return Result.error(result.getMessage());
        }

        if (!this.hyShippingNoteService.updateStatusByZybShippingNumber(
                hyShippingNote.getShippingNoteNumber(), ShippingStatus.已交货.getValue(), new Date(), null, null)) {
            return Result.error("终止围栏失败");
        }

        return Result.OK("操作成功");
    }


    @AutoLog(value = "运单表-派单")
    @ApiOperation(value = "运单表-派单", notes = "运单表-派单")
    @PutMapping(value = "/paidan")
//	@RequiresPermissions("shipping:paidan")
    public Result<?> paidan(@RequestBody JSONObject jsonObject) {

        String orderId = jsonObject.getString("orderId");
        String vehicleId = jsonObject.getString("vehicleId");
        String driverId = jsonObject.getString("driverId");
        String shippingType = jsonObject.getString("shippingType");
        String strshippingUnitPrice = jsonObject.getString("shippingUnitPrice");
        HyOrder order = hyOrderService.getById(orderId);
        if (StringUtils.isEmpty(shippingType)){
            shippingType=order.getShippingType();
        }
        if (StringUtils.isEmpty(strshippingUnitPrice)){
            strshippingUnitPrice=order.getShippingUnitPrice().toString();
        }
        HyStatusCheckUtil.checkShippingType(shippingType);
        BigDecimal shippingUnitPrice = new BigDecimal(strshippingUnitPrice);
        if (shippingUnitPrice.compareTo(BigDecimal.ZERO) <= 0) {
            return Result.error("运费单价错误");
        }
        if (!shippingType.equals(order.getShippingType())){
            return Result.error("运费计算方式与货源不一致，请重新选择");
        }
        //代收人模式
        if (shippingType.equals(ShippingTyeEnum.SHIPPING_TYE_1.getCode())&&order.getPayType().equals(PayConstants.PAY_TYPE.BY_CARRIER)&&shippingUnitPrice.compareTo(order.getCarrierUnitFee())<0){
            return Result.error("运费单价不能小于代收人运费单价");
        }
        if (shippingType.equals(ShippingTyeEnum.SHIPPING_TYE_4.getCode())&&order.getPayType().equals(PayConstants.PAY_TYPE.BY_CARRIER)&&shippingUnitPrice.compareTo(order.getCarrierUnitFee())<0){
            return Result.error("运费不能小于代收人运费");
        }
        //预付模式
        if (shippingType.equals(ShippingTyeEnum.SHIPPING_TYE_1.getCode())&&order.getPayType().equals(PayConstants.PAY_TYPE.BY_PREPAY)&&shippingUnitPrice.compareTo(order.getPreUnitFee())<0){
            return Result.error("运费单价不能小于预付运费单价");
        }
        if (shippingType.equals(ShippingTyeEnum.SHIPPING_TYE_4.getCode())&&order.getPayType().equals(PayConstants.PAY_TYPE.BY_PREPAY)&&shippingUnitPrice.compareTo(order.getPreUnitFee())<0){
            return Result.error("运费不能小于预付运费");
        }


        order.setShippingUnitPrice(shippingUnitPrice);
        order.setShippingType(shippingType);

        if (StringUtils.isEmpty(orderId)) {
            return Result.error("货源信息不能为空");
        }
        if (StringUtils.isEmpty(driverId)) {
            return Result.error("司机信息不能为空");
        }
        if (StringUtils.isEmpty(vehicleId)) {
            return Result.error("车辆信息不能为空");
        }

        if (order == null) {
            return Result.error("货源信息不存在");
        }

        if ("8".equals(order.getOrderStatus())) {
            return Result.error("该货源已完结,不能接单");
        }
        if (!"2".equals(order.getOrderStatus())) {
            return Result.error("该货源未发布,不能接单");
        }

        String izUsedGas = jsonObject.getString("izUsedGas");
        String gasRechargeAmount = jsonObject.getString("gasRechargeAmount");
        if (izUsedGas != null) {
            if (!"0".equals(izUsedGas)) {
                if (StringUtils.isEmpty(gasRechargeAmount)) {
                    return Result.error("充值金额不能为空");
                } else {
                    order.setGasRechargeAmount(new BigDecimal(gasRechargeAmount));
                }
            }
            order.setIzUsedGas(izUsedGas);
        }

        if (!userUtil.isSys()) {
            SysUser user = userUtil.getUser();
            if (!"5".equals(user.getUType())) {
                HyCustomer customer = userUtil.getCustomer();
                if (customer == null) {
                    return Result.error("货主信息不存在!");
                }
                //司机 货主添加关系表
                hyDriverCustomerService.addDriverCustomer(driverId, customer.getId());
                hyDriverCustomerService.addVehicleCustomer(vehicleId, customer.getId());
                if ("3".equals(order.getOrderMode())) {
                    if (!StringUtils.equals(order.getAgentId(), customer.getId())
                            && !StringUtils.equals(order.getCustomerId(), customer.getId())
                            ) {
                        return Result.error("货源信息错误!");
                    }
                } else {
                    if (!StringUtils.equals(order.getCustomerId(), customer.getId())) {
                        return Result.error("货源信息错误!");
                    }
                }
            }

        }

        HyDriver driver = hyDriverService.getById(driverId);
        if (driver == null) {
            return Result.error("司机信息不存在");
        }

//        if ("3".equals(driver.getExamineStatus())) {
//            return Result.error("司机未审核通过，不能派单");
//        }
        HySetting hySetting = settingService.getByTag("checkValidDriver");
        if (hySetting!=null&&hySetting.getData().equals("1")){
            Result result = hyDriverService.checkValidDriver(driver);
            if (result.getCode() == 500) {
                return Result.error(result.getMessage());
            }
        }
        /*Result result = hyDriverService.checkValidDriver(driver);
        if (result.getCode() == 500) {
            return Result.error(result.getMessage());
        }*/

        HyVehicle vehicle = hyVehicleService.getById(vehicleId);
        if (vehicle == null) {
            return Result.error("车辆信息不存在");
        }
        if (!"2".equals(vehicle.getExamineStatus())) {
            return Result.error("车辆信息未通过审核");
        }
        if ("0".equals(vehicle.getIzUsed())){
            return Result.error("选择的车辆未启用，请重新选择");
        }
        //检查车辆是否是司机的
        HyDriverVehicle driverVehicle = hyDriverVehicleService.getInfoByDriverIdAndVehicleId(driverId, vehicleId);
        if (driverVehicle == null) {
            return Result.error("所选车辆不属于司机");
        }
        //查找司机默认银行卡
        HyDriverBank defaultDriverBank = hyDriverBankService.getDefaultDriverBank(driverId);
        String driverBankId = "";
        if (defaultDriverBank != null) {
            driverBankId = defaultDriverBank.getId();
        }
        Result r = hyShippingNoteService.addByOrder(order, driver, vehicle, null, "", "", driverBankId);
        return r;
    }

    @AutoLog(value = "运单表-批量派单")
    @ApiOperation(value = "运单表-批量派单", notes = "运单表-批量派单")
    @PutMapping(value = "/batchPaiDan")
    @Transactional
    public Result<?> batchPaiDan(@RequestBody JSONObject jsonObject) {
        String orderId = jsonObject.getString("orderId");
        String driverIds = jsonObject.getString("driverIds");
        String shippingType = jsonObject.getString("shippingType");
        String strshippingUnitPrice = jsonObject.getString("shippingUnitPrice");
        if (StringUtils.isEmpty(orderId)) {
            return Result.error("货源信息不能为空");
        }
        if (StringUtils.isEmpty(driverIds)) {
            return Result.error("司机信息不能为空");
        }
        if (StringUtils.isEmpty(strshippingUnitPrice)) {
            return Result.error("运费单价不能为空");
        }
        HyStatusCheckUtil.checkShippingType(shippingType);
        BigDecimal shippingUnitPrice = new BigDecimal(strshippingUnitPrice);
        if (shippingUnitPrice.compareTo(BigDecimal.ZERO) <= 0) {
            return Result.error("运费单价错误");
        }

        HyOrder order = hyOrderService.getById(orderId);
        if (order == null) {
            return Result.error("货源信息不存在");
        }
        if ("8".equals(order.getOrderStatus())) {
            return Result.error("该货源已完结,不能接单");
        }
        if (!"2".equals(order.getOrderStatus())) {
            return Result.error("该货源未发布,不能接单");
        }
        String orderMode = order.getOrderMode();
        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(order.getAgentId(), customer.getId())
                        && !StringUtils.equals(order.getCustomerId(), customer.getId())
                        ) {
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(order.getCustomerId(), customer.getId())) {
                    return Result.error("数据错误!");
                }
            }
        }

        List<HyOrderSendAddress> sendList = hyOrderSendAddressService.getListByOrderId(orderId);
        if (sendList.size() == 0) {
            return Result.error("货源发货地址不能为空");
        }
        List<HyOrderReceiveAddress> receiveList = hyOrderReceiveAddressService.getListByOrderId(orderId);
        if (receiveList.size() == 0) {
            return Result.error("货源收货地址不能为空");
        }
        //油气
        String izUsedGas = jsonObject.getString("izUsedGas");
        if (StringUtils.isEmpty(izUsedGas)) {
            return Result.error("油气充值方式错误");
        }
        BigDecimal gasRechargeAmount = BigDecimal.ZERO;
        if (!"0".equals(izUsedGas)) {
            String sgasRechargeAmount = jsonObject.getString("gasRechargeAmount");
            if (StringUtils.isEmpty(sgasRechargeAmount)) {
                return Result.error("充值金额不能为空");
            }
            gasRechargeAmount = new BigDecimal(sgasRechargeAmount);
            if (gasRechargeAmount.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("油气金额错误");
            }
        }
        BigDecimal goodsWeightLoading = null;
        BigDecimal costPay = null;
        BigDecimal costPay1 = null;
        BigDecimal costPay2 = null;
        BigDecimal costPay3 = null;
        //支付计划
        String izUsedPayPlan = jsonObject.getString("izUsedPayPlan");
        if ("1".equals(izUsedPayPlan)) {
            HyStatusCheckUtil.checkPlanFee_PayType(order.getPayType());
            HyStatusCheckUtil.checkPlanFee_OrderMode(orderMode);//检查订单模式

            String strgoodsWeightLoading = jsonObject.getString("goodsWeightLoading");
            if (StringUtils.isEmpty(strgoodsWeightLoading)) {
                return Result.error("装载量不能为空");
            }
            goodsWeightLoading = new BigDecimal(strgoodsWeightLoading);
            if (goodsWeightLoading.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("装载量错误");
            }
            if ("4".equals(shippingType)) {
                costPay = shippingUnitPrice;
            } else {
                costPay = goodsWeightLoading.multiply(shippingUnitPrice);
            }
            String strCostPay1 = jsonObject.getString("costPay1");
            if (StringUtils.isEmpty(strgoodsWeightLoading)) {
                return Result.error("首付不能为空");
            }
            String strCostPay2 = jsonObject.getString("costPay2");
            if (StringUtils.isEmpty(strgoodsWeightLoading)) {
                return Result.error("到付不能为空");
            }
            String strCostPay3 = jsonObject.getString("costPay3");
            if (StringUtils.isEmpty(strgoodsWeightLoading)) {
                return Result.error("尾款不能为空");
            }
            costPay1 = new BigDecimal(strCostPay1);//首付
            if (costPay1.compareTo(BigDecimal.ZERO) < 0) {
                return Result.error("首付运费错误");
            }
            costPay2 = new BigDecimal(strCostPay2);//到付
            if (costPay2.compareTo(BigDecimal.ZERO) < 0) {
                return Result.error("到付运费错误");
            }
            costPay3 = new BigDecimal(strCostPay3);//尾款
            if (costPay3.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("尾款运费错误");
            }
            BigDecimal cost = costPay1.add(costPay2).add(costPay3);
            if (gasRechargeAmount != null) {
                cost = cost.add(gasRechargeAmount);
            }
            if (costPay.compareTo(cost) != 0) {
                return Result.error("运费计算错误");
            }
        }
        String customerId = order.getCustomerId();
        if (StringUtils.isEmpty(customerId)) {
            return Result.error("货主信息不存在");
        }
        HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(order.getCustomerId());
        if (customerCompany == null) {
            return Result.error("未找到货主签约信息");
        }
        String companyId = customerCompany.getCompanyId();
        //司机信息
        List<HyDriver> hyDrivers = hyDriverService.listByIds(Arrays.asList(driverIds.split(",")));
        if (hyDrivers.size() == 0) {
            return Result.error("未找到司机信息");
        }

//        for (HyDriver hyDriver : hyDrivers) {
//            if (!"2".equals(hyDriver.getExamineStatus())) {
//                return Result.error("列表中存在未审核通过的司机");
//            }
//        }

        //todo司机 货主添加关系表
        hyDriverCustomerService.addDriversCustomer(driverIds, customerId);

        List<HyShippingNote> shippingNotes = new ArrayList<>();
        for (HyDriver hyDriver : hyDrivers) {
            HyShippingNote hyShippingNote = hyShippingNoteService.addByOrder(order, hyDriver, companyId);
            hyShippingNote.setShippingStatus(ShippingStatus.待接单.getValue());//设置为待接单状态
            hyShippingNote.setStatusDtReceive(null);//接单时间
            hyShippingNote.setIzUsedGas(izUsedGas);//油气
            hyShippingNote.setGasRechargeAmount(gasRechargeAmount);
            hyShippingNote.setShippingUnitPrice(shippingUnitPrice);
            hyShippingNote.setShippingType(shippingType);
            if ("1".equals(izUsedPayPlan)) {
                hyShippingNote.setGoodsWeightLoading(goodsWeightLoading);
                hyShippingNote.setGoodsWeightUnloading(goodsWeightLoading);//装卸货量相同
                hyShippingNote.setIzUsedPayPlan("1");
                hyShippingNote.setCostPay(costPay);//司机运费
                hyShippingNote.setCostPay1(costPay1);//首付
                hyShippingNote.setCostPay2(costPay2);//到付
                hyShippingNote.setCostPayShipping(costPay3);//尾款
                //计算货主服务费等其他项
                HyCalcFeeUtil.calcPayPlan(hyShippingNote, customerCompany);
            } else {
                hyShippingNote.setIzUsedPayPlan("0");
            }

            HyCompanyConfig hyCompanyConfig = this.companyConfigService.getByCompanyId(customerCompany.getCompanyId());
            //1.辽宁航信税务平台,创建运单条件：司机和车辆同时上传成功
            log.info("校验辽宁税务司机， {} - {} - {} - {}",customerCompany.getCompanyId(), hyCompanyConfig.getTaxUploadType(), hyShippingNote.getShippingNoteNumber(), hyDriver.getLnTaxUploadStatus());
            if (HyCfgUtil.isUsed2("liaoning_tax_report")) {
                if (3 == hyCompanyConfig.getTaxUploadType().intValue()) {
                    hyShippingNote.setAlctIdentification("1");
                    if (StringUtils.isNotEmpty(hyDriver.getLnTaxUploadStatus())) {
                        boolean bDriver = hyDriver.getLnTaxUploadStatus().startsWith("1");
                        if (!bDriver) {
                            return Result.error("司机税务上报状态错误,请先上报数据");
                        }
                    } else {
                        return Result.error("司机数据未上报辽宁税务");
                    }

//                if (StringUtils.isNotEmpty(hyDriver.getLnTaxUploadStatus())) {
//                    List<String> driverSt = Arrays.asList(hyDriver.getLnTaxUploadStatus().split("\\|")).stream().distinct().collect(
//                            Collectors.toList());
//                    if (driverSt.size() != 1) {
//                        return Result.error("司机税务状态错误,请先上报数据");
//                    }
//                } else {
//                    return Result.error("司机数据未上报辽宁税务");
//                }

                    //2.辽宁航信税务平台 创建运单条件2: 如果开启实名认证
                    String authFlag = HyCfgUtil.getCfgItem2("liaoning_tax_report", "realname_auth");
                    if ("1".equals(authFlag)) {
                        Result rDriverAuth = this.shippingNoteApiAlct56Service.queryDriverForAuth(hyDriver);
                        //如果返回-3，会返回微信认证链接，需要司机去认证
                        if (-3 == rDriverAuth.getCode()) {
                            return Result.error(-3, hyDriver.getDriverName() + " 未实名认证，请先通过司机App进行实名认证");
                        }
                    }

                    //辽宁税务上报，必须税务平台返回创建成功后才能创建运单
                    Result result = this.shippingNoteApiAlct56Service.createShippingNote(hyShippingNote);
                    if (!result.getCode().equals(CommonConstant.SC_OK_200)) {
                        return Result.error("税务系统返回错误: " + result.getMessage());
                    }
                }
            }

            if (HyCfgUtil.isUsed2("ordos_report")) {
                log.info("校验鄂尔多斯市上报司机、车辆, {} - {} - {} - {}", customerCompany.getCompanyId(), hyCompanyConfig.getParkReportPlatformType(), hyShippingNote.getShippingNoteNumber(), hyDriver.getZjUploadStatus());
                if (hyCompanyConfig.getParkReportPlatformType().intValue() == 200) {
                    if (!"1".equals(hyDriver.getZjUploadStatus())) {
                        return Result.error("司机数据未上报鄂尔多斯市监管平台");
                    }
                }
            }

            shippingNotes.add(hyShippingNote);
        }
        hyShippingNoteService.saveBatch(shippingNotes);

        //运单收发货地址
        List<HyShippingNoteSendAddress> shippingNoteSendAddresses = new ArrayList<>();
        List<HyShippingNoteReceiveAddress> shippingNoteReceiveAddresses = new ArrayList<>();
        for (HyShippingNote shippingNote : shippingNotes) {
            //发货地址
            for (HyOrderSendAddress hyOrderSendAddress : sendList) {
                HyShippingNoteSendAddress shippingNoteSendAddress = new HyShippingNoteSendAddress();
                BeanUtils.copyProperties(hyOrderSendAddress, shippingNoteSendAddress);
                shippingNoteSendAddress.setId(null);
                shippingNoteSendAddress.setShippingId(shippingNote.getId());
                shippingNoteSendAddresses.add(shippingNoteSendAddress);
            }
            //收货地址
            for (HyOrderReceiveAddress receiveAddress : receiveList) {
                HyShippingNoteReceiveAddress shippingNoteReceiveAddress = new HyShippingNoteReceiveAddress();
                BeanUtils.copyProperties(receiveAddress, shippingNoteReceiveAddress);
                shippingNoteReceiveAddress.setId(null);
                shippingNoteReceiveAddress.setShippingId(shippingNote.getId());
                shippingNoteReceiveAddresses.add(shippingNoteReceiveAddress);
            }
        }
        hyShippingNoteSendAddressService.saveBatch(shippingNoteSendAddresses);
        hyShippingNoteReceiveAddressService.saveBatch(shippingNoteReceiveAddresses);
        return Result.OK("批量派单成功");
    }

    @AutoLog(value = "运单表-变更运费支付计划")
    @ApiOperation(value = "运单表-变更运费支付计划", notes = "运单表-变更运费支付计划")
    @PutMapping(value = "/changePayPlan")
    @Transactional
    public Result<?> changePayPlan(@RequestBody JSONObject jsonObject) {
        String id = jsonObject.getString("id");
        String shippingType = jsonObject.getString("shippingType");
        String strshippingUnitPrice = jsonObject.getString("shippingUnitPrice");
        if (StringUtils.isEmpty(id)) {
            return Result.error("id不能为空");
        }
        if (StringUtils.isEmpty(strshippingUnitPrice)) {
            return Result.error("运费单价不能为空");
        }
        HyStatusCheckUtil.checkShippingType(shippingType);
        BigDecimal shippingUnitPrice = new BigDecimal(strshippingUnitPrice);
        if (shippingUnitPrice.compareTo(BigDecimal.ZERO) <= 0) {
            return Result.error("运费单价错误");
        }
        HyShippingNote shippingNote = hyShippingNoteService.getByIdForUpdate(id);
        if (shippingNote == null) {
            return Result.error("运单信息不存在");
        }
        if (!"1".equals(shippingNote.getIzUsedPayPlan())) {
            return Result.error("不是支付计划运单，不能操作");
        }

        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            if ("3".equals(shippingNote.getOrderMode())) {
                if (!StringUtils.equals(shippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(shippingNote.getCustomerId(), customer.getId())
                        ) {
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(shippingNote.getCustomerId(), customer.getId())) {
                    return Result.error("数据错误!");
                }
            }
        }

        //运单是否支付
        if (hyShippingNoteService.checkIsPay(shippingNote)) {
            return Result.error("运单已支付，不能变更");
        }

        //油气
        String izUsedGas = jsonObject.getString("izUsedGas");
        if (StringUtils.isEmpty(izUsedGas)) {
            return Result.error("油气充值方式参数不能为空");
        }
        BigDecimal gasRechargeAmount = BigDecimal.ZERO;
        if (!"0".equals(izUsedGas)) {
            String sgasRechargeAmount = jsonObject.getString("gasRechargeAmount");
            if (StringUtils.isEmpty(sgasRechargeAmount)) {
                return Result.error("充值金额不能为空");
            }
            gasRechargeAmount = new BigDecimal(sgasRechargeAmount);
            if (gasRechargeAmount.compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("油气金额错误");
            }
        }

        String oldIzUsedGas = shippingNote.getIzUsedGas();
        if (!"0".equals(oldIzUsedGas)) {
            BigDecimal oldGasRechargeAmount = shippingNote.getGasRechargeAmount();
            if (oldGasRechargeAmount == null) {
                oldGasRechargeAmount = BigDecimal.ZERO;
            }
            if ("0".equals(izUsedGas) || gasRechargeAmount.compareTo(oldGasRechargeAmount) != 0) {
                //当变更油气或者油气金额时，检查油气是否已充值完成，如果充值完成，不能变更油气费
                HyShippingNoteGas shippingNoteGas = hyShippingNoteGasService.getByShippingId(shippingNote.getId());
                if (hyShippingNoteGasService.checkRecharge(shippingNoteGas)) {
                    return Result.error("油气已充值,不能变更油气费");
                }
            }
        }
        shippingNote.setIzUsedGas(izUsedGas);
        shippingNote.setGasRechargeAmount(gasRechargeAmount);

        String oldPayType = shippingNote.getPayType();
        boolean ischange = false;
        String payType = jsonObject.getString("payType");
        if (StringUtils.isNotEmpty(payType)) {
            HyStatusCheckUtil.checkPayType(payType);
            if (!StringUtils.equals(oldPayType, payType)) {
                ischange = true;
            }
            shippingNote.setPayType(payType);
            if ("2".equals(payType)) {
                String carrierId = jsonObject.getString("carrierId");
                if (StringUtils.isEmpty(carrierId)) {
                    return Result.error("车队长不能为空");
                }
                String carrierFeeType = jsonObject.getString("carrierFeeType");
                if (StringUtils.isEmpty(carrierFeeType)) {
                    return Result.error("车队长计算方式不能为空");
                }
                String carrierUnitFee = jsonObject.getString("carrierUnitFee");
                if (StringUtils.isEmpty(carrierUnitFee)) {
                    return Result.error("车队长运费单价不能为空");
                }
                if ("1".equals(carrierFeeType) || "2".equals(carrierFeeType)) {
                    shippingNote.setCarrierFeeType(carrierFeeType);
                    shippingNote.setCarrierUnitFee(new BigDecimal(carrierUnitFee));
                } else {
                    shippingNote.setCarrierFeeType("0");
                    shippingNote.setCarrierUnitFee(BigDecimal.ZERO);
                }
                shippingNote.setCarrierId(carrierId);
            } else {
                shippingNote.setCarrierId("");
                shippingNote.setCarrierUnitFee(BigDecimal.ZERO);
            }
        }

        BigDecimal goodsWeightLoading = null;
        BigDecimal costPay = null;
        BigDecimal costPay1 = null;
        BigDecimal costPay2 = null;
        BigDecimal costPay3 = null;
        //支付计划
        String strgoodsWeightLoading = jsonObject.getString("goodsWeightLoading");
        if (StringUtils.isEmpty(strgoodsWeightLoading)) {
            return Result.error("装载量不能为空");
        }
        goodsWeightLoading = new BigDecimal(strgoodsWeightLoading);
        if (goodsWeightLoading.compareTo(BigDecimal.ZERO) <= 0) {
            return Result.error("装载量错误");
        }
        if ("4".equals(shippingType)) {
            costPay = shippingUnitPrice;
        } else {
            costPay = goodsWeightLoading.multiply(shippingUnitPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        String strCostPay1 = jsonObject.getString("costPay1");
        if (StringUtils.isEmpty(strgoodsWeightLoading)) {
            return Result.error("首付不能为空");
        }
        String strCostPay2 = jsonObject.getString("costPay2");
        if (StringUtils.isEmpty(strgoodsWeightLoading)) {
            return Result.error("到付不能为空");
        }
        String strCostPay3 = jsonObject.getString("costPay3");
        if (StringUtils.isEmpty(strgoodsWeightLoading)) {
            return Result.error("尾款不能为空");
        }
        costPay1 = new BigDecimal(strCostPay1);//首付
        if (costPay1.compareTo(BigDecimal.ZERO) < 0) {
            return Result.error("首付运费错误");
        }
        costPay2 = new BigDecimal(strCostPay2);//到付
        if (costPay2.compareTo(BigDecimal.ZERO) < 0) {
            return Result.error("到付运费错误");
        }
        costPay3 = new BigDecimal(strCostPay3);//尾款
        if (costPay3.compareTo(BigDecimal.ZERO) <= 0) {
            return Result.error("尾款运费错误");
        }
        BigDecimal cost = costPay1.add(costPay2).add(costPay3);
        if (gasRechargeAmount != null) {
            cost = cost.add(gasRechargeAmount);
        }
        if (costPay.compareTo(cost) != 0) {
            return Result.error("运费计算错误");
        }

        BigDecimal oldCostPay1 = shippingNote.getCostPay1();
        HyBill bill1 = null;
        if (costPay1.compareTo(oldCostPay1) != 0 || ischange) {
            //检查首付是否支付
            if (BigDecimal.ZERO.compareTo(oldCostPay1) != 0) {
                bill1 = hyBillService.getBillByShippingId(id, "8");
                if (bill1 != null) {
                    if (hyBillService.checkIsPay(bill1)) {
                        return Result.error("首付运费已支付完成，不能修改");
                    }
                    bill1.setAmt(costPay1);
                    bill1.setCustomerAmt(costPay1);
                    bill1.setDriverAmt(costPay1);
                    if ("2".equals(shippingNote.getPayType())) {//车队长运费
                        bill1.setCarrierAmt(costPay1);
                        bill1.setIzCarrierPay("1");
                    } else {
                        bill1.setCarrierAmt(BigDecimal.ZERO);
                        bill1.setIzCarrierPay("0");
                    }
                }
            }
        }
        BigDecimal oldCostPay2 = shippingNote.getCostPay2();
        HyBill bill2 = null;
        if (costPay2.compareTo(oldCostPay2) != 0 || ischange) {
            //检查到付是否支付
            if (BigDecimal.ZERO.compareTo(oldCostPay2) != 0) {
                bill2 = hyBillService.getBillByShippingId(id, "9");
                if (bill2 != null) {
                    if (hyBillService.checkIsPay(bill2)) {
                        return Result.error("到付运费已支付完成，不能修改");
                    }
                    bill2.setAmt(costPay2);
                    bill2.setCustomerAmt(costPay2);
                    bill2.setDriverAmt(costPay2);
                    if ("2".equals(shippingNote.getPayType())) {//车队长运费
                        bill2.setCarrierAmt(costPay2);
                        bill2.setIzCarrierPay("1");
                    } else {
                        bill2.setCarrierAmt(BigDecimal.ZERO);
                        bill2.setIzCarrierPay("0");
                    }
                }
            }
        }
        BigDecimal oldCostPay3 = shippingNote.getCostPayShipping();
        BigDecimal oldCustomerAmt = billService.getCustomerCostPayTotal(shippingNote);

        HyCustomerCompany customerCompany = hyCustomerCompanyService.getByCustomerId(shippingNote.getCustomerId());
        if (customerCompany == null) {
            return Result.error("未找到货主签约信息");
        }

        shippingNote.setShippingType(shippingType);
        shippingNote.setShippingUnitPrice(shippingUnitPrice);
        //计算货主服务费等其他项
        shippingNote.setGoodsWeightLoading(goodsWeightLoading);
        shippingNote.setGoodsWeightUnloading(goodsWeightLoading);//装卸货量相同
//		shippingNote.setIzUsedPayPlan("1");
        shippingNote.setCostPay(costPay);//司机运费
        shippingNote.setCostPay1(costPay1);//首付
        shippingNote.setCostPay2(costPay2);//到付
        shippingNote.setCostPayShipping(costPay3);//尾款
        HyCalcFeeUtil.calcPayPlan(shippingNote, customerCompany);

        String driverBankId = jsonObject.getString("driverBankId");
        String imgLoading = jsonObject.getString("imgLoading");
        String imgUnloading = jsonObject.getString("imgUnloading");
        shippingNote.setDriverBankId(driverBankId);
        if (StringUtils.isNotEmpty(imgLoading)) {
            shippingNote.setImgLoading(imgLoading);
        }
        if (StringUtils.isNotEmpty(imgUnloading)) {
            shippingNote.setImgUnloading(imgUnloading);
        }
        hyShippingNoteService.updateById(shippingNote);
        if (bill1 != null) {
            hyBillService.updateById(bill1);
        }
        if (bill2 != null) {
            hyBillService.updateById(bill2);
        }

        BigDecimal newCustomerAmt = billService.getCustomerCostPayTotal(shippingNote);
        if (costPay3.compareTo(oldCostPay3) != 0 || oldCustomerAmt.compareTo(newCustomerAmt) != 0 || ischange) {
            HyBill bill3 = hyBillService.getBillByShippingId(id, "1");
            if (bill3 != null) {
                if (hyBillService.checkIsPay(bill3)) {
                    throw new JeecgBootException("尾款已支付完成，不能修改");
                }
                bill3.setAmt(newCustomerAmt);
                bill3.setCustomerAmt(newCustomerAmt);
                bill3.setDriverAmt(costPay3);
                if ("2".equals(shippingNote.getPayType())) {//车队长运费
                    BigDecimal carrierFee = billService.getCarrierBillAmt(shippingNote);
                    bill3.setCarrierAmt(carrierFee);
                    bill3.setIzCarrierPay("1");
                } else {
                    bill3.setCarrierAmt(BigDecimal.ZERO);
                    bill3.setIzCarrierPay("0");
                }
                hyBillService.updateById(bill3);
            }
        }
        return Result.OK("变更成功");
    }

    @ApiOperation(value = "运单表-查询支付计划支付状态", notes = "运单表-查询支付计划支付状态")
    @GetMapping(value = "/getPayPlanST")
    public Result<?> getPayPlanST(@RequestParam(name = "shippingId", required = true) String shippingId) {
        List<HyBill> bill = hyBillService.getBillListByShippingId(shippingId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("shoufu", "0");
        jsonObject.put("daofu", "0");
        for (HyBill hyBill : bill) {
            if (BillTypeEnum.PLAN_PAY_SHOUFU.value.equals(hyBill.getBillType())) {
                String payStatus = hyBill.getPayStatus();
                jsonObject.put("shoufu", payStatus);
            }
            if (BillTypeEnum.PLAN_PAY_DAOFU.value.equals(hyBill.getBillType())) {
                String payStatus = hyBill.getPayStatus();
                jsonObject.put("daofu", payStatus);
            }
        }
        return Result.OK(jsonObject);
    }

    @AutoLog(value = "运单表-派车")
    @ApiOperation(value = "运单表-派车", notes = "运单表-派车")
    @PutMapping(value = "/paiche")
    @Transactional
    public Result<?> paiche(@RequestBody JSONObject jsonObject) {
        String id = jsonObject.getString("id");
        if (StringUtils.isEmpty(id)) {
            return Result.error("id不能为空");
        }
        String vehicleId = jsonObject.getString("vehicleId");
        if (StringUtils.isEmpty(vehicleId)) {
            return Result.error("车辆id不能为空");
        }
        HyShippingNote shippingNote = hyShippingNoteService.getByIdForUpdate(id);
        if (shippingNote == null) {
            return Result.error("运单信息不存在");
        }
        if (!"0".equals(shippingNote.getShippingStatus())) {
            return Result.error("该运单已接单,不能重复操作");
        }
        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            if ("3".equals(shippingNote.getOrderMode())) {
                if (!StringUtils.equals(shippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(shippingNote.getCustomerId(), customer.getId())
                        ) {
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(shippingNote.getCustomerId(), customer.getId())) {
                    return Result.error("数据错误!");
                }
            }
        }
        String driverBankId = jsonObject.getString("driverBankId");
        if (StringUtils.isNotEmpty(driverBankId)) {
            HyDriverBank driverBank = hyDriverBankService.getById(driverBankId);
            if (driverBank == null) {
                return Result.error("银行卡信息不存在");
            }
            if (!StringUtils.equals(driverBank.getDriverId(), shippingNote.getDriverId())) {
                return Result.error("银行卡信息错误");
            }
        } else {
            //查找司机默认银行卡
            HyDriverBank defaultDriverBank = hyDriverBankService.getDefaultDriverBank(shippingNote.getDriverId());
            if (defaultDriverBank != null) {
                driverBankId = defaultDriverBank.getId();
            }

            if (StringUtils.isEmpty(driverBankId)) {
                HyCustomerConfig customerConfig = customerConfigService.getByCustomerId(shippingNote.getCustomerId());
                if (customerConfig != null) {
                    if ("1".equals(customerConfig.getIsOrderBank())) {
                        return Result.error("请选择银行卡");
                    }
                }
            }
        }
        shippingNote.setDriverBankId(driverBankId);

        return hyShippingNoteService.jiedan(shippingNote, vehicleId);
    }
    //endregion

    //region 签收
    @AutoLog(value = "运单表-签收")
    @ApiOperation(value = "运单表-签收", notes = "运单表-签收")
    @PutMapping(value = "/submitCheck")
    @RequiresPermissions("shipping:submitCheck")
    @Transactional
    public Result<?> submitCheck(@RequestParam(name = "id", required = true) String id) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getByIdForUpdate(id);
        if (hyShippingNote == null) {
            return Result.error("该运单不存在");
        }
        String shippingStatus = hyShippingNote.getShippingStatus();
        if (!"4".equals(shippingStatus)) {
            log.error("运单未交货,不能签收{}", hyShippingNote.getShippingNoteNumber());
            return Result.error("运单未交货,不能签收");
        }

        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            String orderMode = hyShippingNote.getOrderMode();
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                        ) {
                    log.error("签收数据错误 {} - {} - {}", hyShippingNote.getAgentId(),
                            hyShippingNote.getCustomerId(), customer.getId());
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                    log.error("签收数据错误 {} - {}", hyShippingNote.getCustomerId(), customer.getId());
                    return Result.error("数据错误!");
                }
            }
        }

        if (hyShippingNote.getGoodsWeightLoading() == null) {
            return Result.error("装货数量不能为空");
        }
        if ("1".equals(settingService.getSettingValueByTag2("usedLoadingImg"))) {
            if (StringUtils.isEmpty(hyShippingNote.getImgLoading())) {
                log.error("装货凭证照片不能为空,不能签收{}", hyShippingNote.getShippingNoteNumber());
                return Result.error("装货凭证照片不能为空");
            }
        }

        if (hyShippingNote.getGoodsWeightUnloading() == null) {
            return Result.error("卸货数量不能为空");
        }
        if ("1".equals(settingService.getSettingValueByTag2("usedUnLoadingImg"))) {
            if (StringUtils.isEmpty(hyShippingNote.getImgUnloading())) {
                log.error("卸货凭证照片不能为空,不能签收{}", hyShippingNote.getShippingNoteNumber());
                return Result.error("卸货凭证照片不能为空");
            }
        }

        //核算
        hyShippingNoteService.calcCoss(hyShippingNote);

        hyShippingNote.setShippingStatus(ShippingStatus.已签收.getValue());//设置状态为已交货
        hyShippingNote.setStatusDtSign(new Date());//签收时间

        hyShippingNote.setShippingPayStatus("1"); //申请对账
        hyShippingNote.setPayDtSubmitCheck(new Date());//申请对账时间

        String realName = UserUtil.getLoginUser().getRName();
        hyShippingNote.setQsr(realName);//设置签收人

        if (hyShippingNote.getIzDriverPayset().equals("1")) {
            hyShippingNote.setSettlementTon(hyShippingNote.getGoodsWeightLoading());
        } else if (hyShippingNote.getIzDriverPayset().equals("2")) {
            hyShippingNote.setSettlementTon(hyShippingNote.getGoodsWeightUnloading());
        } else if (hyShippingNote.getIzDriverPayset().equals("0")) {
            if (hyShippingNote.getGoodsWeightLoading().compareTo(hyShippingNote.getGoodsWeightUnloading()) < 0) {
                hyShippingNote.setSettlementTon(hyShippingNote.getGoodsWeightLoading());
            } else {
                hyShippingNote.setSettlementTon(hyShippingNote.getGoodsWeightUnloading());
            }
        }

        //如果是辽宁税务的运单，需要同步轨迹，这里不用异步事件要确保轨迹上传
        if ("1".equals(hyShippingNote.getAlctIdentification())) {
            Result r = this.shippingNoteApiAlct56Service.syncTraces(hyShippingNote);
            if (!r.getCode().equals(CommonConstant.SC_OK_200)) {
                return r;
            }
        }

        hyShippingNoteService.updateById(hyShippingNote);

        //签收订阅消息
//        if ("1".equals(hyShippingNote.getTosIdentification())) {
//            GenMqUtil.sendMsg(EnumGenHandler.SHIPPING_DISCHARGE, "TosApi", hyShippingNote);
//        }

        //大屏发送websocket消息
//		GenMqUtil.sendMsg(EnumGenHandler.DAPING, "", hyShippingNote);

//		publisherRedisMessageService.publisherRedisMessage(RedisChannelEnum.SHIPPING_DISCHARGE,hyShippingNote);
        //if ("1".equals(hyShippingNote.getIzDbOrder())) {
         //   this.applicationEventPublisher.publishEvent(DeBangEvent.builder()
         //           .uploadType("DA_CHE")
         //           .shippingId(hyShippingNote)
         //           .build());
//            GenMqUtil.sendMsg(EnumGenHandler.DE_BANG, "DA_CHE", hyShippingNote);
        //}
        return Result.OK("操作成功!");
    }

    @AutoLog(value = "运单表-签收")
    @PutMapping(value = "/submitCheck2")
    @RequiresPermissions("shipping:submitCheck")
    @Transactional
    public Result<?> submitCheck2(@RequestBody HyShippingNote hyShippingNote) {
        HyShippingNote old = hyShippingNoteService.getByIdForUpdate(hyShippingNote.getId());
        if (old == null) {
            return Result.error("数据不存在!");
        }
        String shippingStatus = old.getShippingStatus();
        if (!"10".equals(hyShippingNote.getShippingPayStatus())) {
            if (!"1".equals(shippingStatus) && !"3".equals(shippingStatus) && !"4".equals(shippingStatus)) {
                return Result.error("不能修改!");
            }
        }

        if (hyShippingNote.getGoodsWeightLoading() == null) {
            log.error("装货数量不能为空,不能签收{}", hyShippingNote.getShippingNoteNumber());
            return Result.error("装货数量不能为空");
        }

        if (hyShippingNote.getGoodsWeightUnloading() == null) {
            log.error("卸货数量不能为空,不能签收{}", hyShippingNote.getShippingNoteNumber());
            return Result.error("卸货数量不能为空");
        }

        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            String orderMode = hyShippingNote.getOrderMode();
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                        ) {
                    log.error("签收数据错误 {} - {} - {}", hyShippingNote.getAgentId(),
                            hyShippingNote.getCustomerId(), customer.getId());
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                    log.error("签收数据错误 {} - {}", hyShippingNote.getCustomerId(), customer.getId());
                    return Result.error("数据错误!");
                }
            }
        }

        String imgLoading = hyShippingNote.getImgLoading();
        String imgUnloading = hyShippingNote.getImgUnloading();

        if ("1".equals(settingService.getSettingValueByTag2("usedLoadingImg"))) {
            if (StringUtils.isEmpty(imgLoading)) {
                log.error("装货凭证不能为空,不能签收{}", hyShippingNote.getShippingNoteNumber());
                return Result.error("装货凭证不能为空!");
            }
        }
        if ("1".equals(settingService.getSettingValueByTag2("usedUnLoadingImg"))) {
            if (StringUtils.isEmpty(imgUnloading)) {
                log.error("卸货凭证不能为空,不能签收{}", hyShippingNote.getShippingNoteNumber());
                return Result.error("卸货凭证不能为空!");
            }
        }

        if (hyShippingNote.getStatusDtLoading() == null) {
            log.error("装货时间不能为空,不能签收{}", hyShippingNote.getShippingNoteNumber());
            return Result.error("装货时间不能为空!");
        }

        if (hyShippingNote.getStatusDtUnloading() == null) {
            log.error("卸货时间不能为空,不能签收{}", hyShippingNote.getShippingNoteNumber());
            return Result.error("卸货时间不能为空!");
        }

        //检查油气(万金油)
        //Modified at 2023-08-18 for 导入的运单跳过万金油校验
        if (!"1".equals(hyShippingNote.getImportFlag())) {
            if ("1".equals(hyShippingNote.getIzUsedGas()) || "3".equals(hyShippingNote.getIzUsedGas())) {
                HyShippingNoteGas gas = hyShippingNoteGasService.getByShippingId(hyShippingNote.getId());
                if (gas == null) {
                    return Result.error("未分配油气，请先分配油气");
                }
            }
        }

        String loadingSceneImg = hyShippingNote.getLoadingSceneImg();
        String unloadingSceneImg = hyShippingNote.getUnloadingSceneImg();

        HyCompanyConfig companyConfig = companyConfigService.getByCompanyId(old.getCompanyId());
        if (companyConfig != null && 1 == companyConfig.getScenePhoto()) {
            if (StringUtils.isEmpty(loadingSceneImg)) {
                log.error("装货现场照片不能为空,不能签收{}", hyShippingNote.getShippingNoteNumber());
                return Result.error("装货现场照片不能为空!");
            }
            if (StringUtils.isEmpty(unloadingSceneImg)) {
                log.error("卸货现场照片不能为空,不能签收{}", hyShippingNote.getShippingNoteNumber());
                return Result.error("卸货现场照片不能为空!");
            }
            //是否修改装卸货现场图片 ，如修改重新添加水印。
            if (!StringUtils.equals(loadingSceneImg, old.getLoadingSceneImg())) {
                String waterMarkImg = hyShippingNoteService.buildWaterMarkImg(old, loadingSceneImg, "send");
                hyShippingNote.setLoadingSceneImg(StringUtils.isNotEmpty(waterMarkImg) ? waterMarkImg : loadingSceneImg);
            }
            if (!StringUtils.equals(unloadingSceneImg, old.getUnloadingSceneImg())) {
                String waterMarkImg = hyShippingNoteService.buildWaterMarkImg(old, unloadingSceneImg, "receive");
                hyShippingNote.setUnloadingSceneImg(StringUtils.isNotEmpty(waterMarkImg) ? waterMarkImg : unloadingSceneImg);
            }
        }

        //装卸货榜单加水印
        hyShippingNoteService.getWatermarkPic(hyShippingNote, imgLoading, imgUnloading,
                old.getImgLoading(), old.getImgUnloading()
        );

        //核算
        hyShippingNoteService.calcCoss(hyShippingNote);
        hyShippingNote.setShippingStatus(ShippingStatus.已签收.getValue());//设置状态为已交货
        hyShippingNote.setStatusDtSign(new Date());//签收时间

        //业务审核是否开启
        if (HyCfgUtil.isUsed2("isOpenYewu")) {
            hyShippingNote.setShippingPayStatus("9"); //业务审核
        } else {
            hyShippingNote.setShippingPayStatus("1"); //申请对账
            hyShippingNote.setPayDtSubmitCheck(new Date());//申请对账时间
        }

        if (hyShippingNote.getIzDriverPayset().equals("1")) {
            hyShippingNote.setSettlementTon(hyShippingNote.getGoodsWeightLoading());
        } else if (hyShippingNote.getIzDriverPayset().equals("2")) {
            hyShippingNote.setSettlementTon(hyShippingNote.getGoodsWeightUnloading());
        } else if (hyShippingNote.getIzDriverPayset().equals("0")) {
            if (hyShippingNote.getGoodsWeightLoading().compareTo(hyShippingNote.getGoodsWeightUnloading()) < 0) {
                hyShippingNote.setSettlementTon(hyShippingNote.getGoodsWeightLoading());
            } else {
                hyShippingNote.setSettlementTon(hyShippingNote.getGoodsWeightUnloading());
            }
        }

        if ("1".equals(hyShippingNote.getAlctIdentification())) {
            Result r = this.shippingNoteApiAlct56Service.syncTraces(hyShippingNote);
            if (!r.getCode().equals(CommonConstant.SC_OK_200)) {
                return r;
            }
        }

        String realName = UserUtil.getLoginUser().getRName();
        hyShippingNote.setQsr(realName);//设置签收人

        hyShippingNoteService.updateById(hyShippingNote);

        //Added start at 2024-04-11 for
        //签收时如果是安徽监管尝试发送运单1数据，对账提交时发送运单2数据，最后上报时只上报运单3，解决安徽分段上报时监管侧消息队列消费问题
        String realtimeUpload = HyCfgUtil.getCfgItem2("anhui_report","realtime_upload");
        if (StrUtil.isNotEmpty(realtimeUpload)) {
            if (companyConfig.getReportPlatformType().equals(ReportPlatformEnum.REPORT_PLATFORM_AH.getCode())) {
                log.info("发送异步事件，上报实时运单1 {}", hyShippingNote.getShippingNoteNumber());
                this.applicationEventPublisher.publishEvent(AhRealtimeReportEvent.builder()
                        .shippingId(hyShippingNote.getId())
                        .ahRealtimeType(AhRealtimeEnum.AH_REALTIME_REPORT_STEP1)
                        .build()
                );
            }
        }
        //Added end at 2024-04-11

        //Modified start at 2024-07-15 for 重构装货运输消息通知功能
        this.applicationEventPublisher.publishEvent(ShippingNoticeEvent.builder()
                .msgType(MessageTypeEnum.MESSAGE_TYPE_SIGN.getCode())
                .shippingId(hyShippingNote.getId())
                .shippingNoteNumber(hyShippingNote.getShippingNoteNumber())
                .driverId(hyShippingNote.getDriverId())
                .vehicleId(hyShippingNote.getVehicleId())
                .dateTime(new Date())
                .loginUser(UserUtil.getLoginUser())
                .build());
        //签收订阅消息
        //if ("1".equals(hyShippingNote.getTosIdentification())) {
        //    GenMqUtil.sendMsg(EnumGenHandler.SHIPPING_DISCHARGE, "TosApi", hyShippingNote);
        //}
        //Modified end at 2024-07-15 for 重构装货运输消息通知功能

        return Result.OK("操作成功!");
    }

    @AutoLog(value = "分配油气（万金油）")
    @PutMapping(value = "/useGas")
    @RequiresPermissions("shipping:submitCheck")
    public Result<?> useGas(@RequestParam(name = "id", required = true) String id) {
        //1万金油 3 油气平台
        return gasService.useGas(id);

    }

    @AutoLog(value = "运单表-批量签收")
    @ApiOperation(value = "运单表-批量签收", notes = "运单表-批量签收")
    @PostMapping(value = "/submitCheckBatch")
    @RequiresPermissions("shipping:submitCheckBatch")
    @Transactional
    public Result<?> submitCheckBatch(@RequestParam(name = "ids", required = true) String ids) {
        if (StringUtils.isBlank(ids)) {
            return Result.error("ids不能为空!");
        }
        List<HyShippingNote> hyShippingNotes = hyShippingNoteService.listByIdsForUpdate(Arrays.asList(ids.split(",")));
        String realName = UserUtil.getLoginUser().getRName();
        boolean issys = userUtil.isSys();
        HyCustomer customer = userUtil.getCustomer();
        if (!issys) {
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
        }
        for (HyShippingNote hyShippingNote : hyShippingNotes) {
            if (!issys) {
                String orderMode = hyShippingNote.getOrderMode();
                if ("3".equals(orderMode)) {
                    if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                            && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                            ) {
                        return Result.error("数据错误!");
                    }
                } else {
                    if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                        return Result.error("数据错误!");
                    }
                }
            }
            //辽宁税务运单请在货主端App进行签收
            if ("1".equals(hyShippingNote.getAlctIdentification())) {
                if (HyCfgUtil.isUsed2("liaoning_tax_report")) {
                    return Result.error("辽宁税务运单请在货主端App进行签收");
                }
            }

            if (!ShippingStatus.已交货.getValue().equals(hyShippingNote.getShippingStatus())) {
                return Result.error("包含未交货状态运单,不能签收!");
            }
            if (hyShippingNote.getGoodsWeightLoading() == null) {
                return Result.error("装货数量不能为空");
            }
            if ("1".equals(settingService.getSettingValueByTag2("usedLoadingImg"))) {
                if (StringUtils.isEmpty(hyShippingNote.getImgLoading())) {
                    return Result.error("装货凭证照片不能为空");
                }
            }
            if (hyShippingNote.getGoodsWeightUnloading() == null) {
                return Result.error("卸货数量不能为空");
            }
            if ("1".equals(settingService.getSettingValueByTag2("usedUnLoadingImg"))) {
                if (StringUtils.isEmpty(hyShippingNote.getImgUnloading())) {
                    return Result.error("卸货凭证照片不能为空");
                }
            }
            //核算
            hyShippingNoteService.calcCoss(hyShippingNote);
            hyShippingNote.setShippingStatus(ShippingStatus.已签收.getValue());//设置状态为已交货
            hyShippingNote.setStatusDtSign(new Date());//签收时间
            hyShippingNote.setQsr(realName);//设置签收人

            if (hyShippingNote.getIzDriverPayset().equals("1")) {
                hyShippingNote.setSettlementTon(hyShippingNote.getGoodsWeightLoading());
            } else if (hyShippingNote.getIzDriverPayset().equals("2")) {
                hyShippingNote.setSettlementTon(hyShippingNote.getGoodsWeightUnloading());
            } else if (hyShippingNote.getIzDriverPayset().equals("0")) {
                if (hyShippingNote.getGoodsWeightLoading().compareTo(hyShippingNote.getGoodsWeightUnloading()) < 0) {
                    hyShippingNote.setSettlementTon(hyShippingNote.getGoodsWeightLoading());
                } else {
                    hyShippingNote.setSettlementTon(hyShippingNote.getGoodsWeightUnloading());
                }
            }

            //业务审核是否开启
            if (HyCfgUtil.isUsed2("isOpenYewu")) {
                hyShippingNote.setShippingPayStatus("9"); //业务审核
            } else {
                hyShippingNote.setShippingPayStatus("1"); //申请对账
                hyShippingNote.setPayDtSubmitCheck(new Date());//申请对账时间
            }

            //Added start at 2024-04-11 for
            //签收时如果是安徽监管尝试发送运单1数据，对账提交时发送运单2数据，最后上报时只上报运单3，解决安徽分段上报时监管侧消息队列消费问题
            String realtimeUpload = HyCfgUtil.getCfgItem2("anhui_report","realtime_upload");
            if (StrUtil.isNotEmpty(realtimeUpload)) {
                HyCompanyConfig companyConfig = this.companyConfigService.getByCompanyId(hyShippingNote.getCompanyId());
                if (companyConfig.getReportPlatformType().equals(ReportPlatformEnum.REPORT_PLATFORM_AH.getCode())) {
                    log.info("发送异步事件，上报实时运单1 {}", hyShippingNote.getShippingNoteNumber());
                    this.applicationEventPublisher.publishEvent(AhRealtimeReportEvent.builder()
                            .shippingId(hyShippingNote.getId())
                            .ahRealtimeType(AhRealtimeEnum.AH_REALTIME_REPORT_STEP1)
                            .build()
                    );
                }
            }
            //Added end at 2024-04-11

            //Modified start at 2024-07-15 for 重构装货运输消息通知功能
            this.applicationEventPublisher.publishEvent(ShippingNoticeEvent.builder()
                    .msgType(MessageTypeEnum.MESSAGE_TYPE_SIGN.getCode())
                    .shippingId(hyShippingNote.getId())
                    .shippingNoteNumber(hyShippingNote.getShippingNoteNumber())
                    .driverId(hyShippingNote.getDriverId())
                    .vehicleId(hyShippingNote.getVehicleId())
                    .dateTime(new Date())
                    .loginUser(UserUtil.getLoginUser())
                    .build());
            //Modified end at 2024-07-15 for 重构装货运输消息通知功能
        }
        this.hyShippingNoteService.updateBatchById(hyShippingNotes);
        return Result.OK("操作成功!");
    }

    //endregion

    @AutoLog(value = "对账-撤销签收")
    @ApiOperation(value = "对账-撤销签收", notes = "对账-撤销签收")
    @PostMapping(value = "/cancelCheck")
    @Transactional
    public Result<?> cancelCheck(@RequestBody HyShippingNoteDTO hyShippingNoteDto) {

        String id = hyShippingNoteDto.getId();
        if (StrUtil.isEmpty(id)) {
            return Result.error("该运单号不能为空");
        }

        HyShippingNote hyShippingNoteDB = this.hyShippingNoteService.getById(id);
        if (null == hyShippingNoteDB) {
            return Result.error("该运单数据不存在");
        }

        String shippingPayStatus = hyShippingNoteDB.getShippingPayStatus();
        if (2 < Integer.valueOf(shippingPayStatus)) {
            return Result.error("该运单已完成提交对账，不能撤销");
        }

        HyShippingNote updateShippingNote = new HyShippingNote();
        updateShippingNote.setId(hyShippingNoteDB.getId());
        updateShippingNote.setShippingStatus(ShippingStatus.已交货.getValue());
        updateShippingNote.setShippingPayStatus(ShippingPayStatus.未对账.getValue());
        if (!this.hyShippingNoteService.updateById(updateShippingNote)) {
            return Result.error("运单撤销签收失败");
        }

        return Result.OK("操作成功");
    }


    //region 对账
    @AutoLog(value = "对账计算")
    @PostMapping(value = "/getCalc")
    public Result<?> getCalc(@RequestBody HyShippingNote hyShippingNote) {
        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            String orderMode = hyShippingNote.getOrderMode();
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                        ) {
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                    return Result.error("数据错误!");
                }
            }
        }
        //前端有个bug,izCaptainShipping没有传过来后期修复
        if (hyShippingNote.getIzCaptainShipping()==null){
            HyShippingNote shippingNote = hyShippingNoteService.getById(hyShippingNote.getId());
            hyShippingNote.setIzCaptainShipping(shippingNote.getIzCaptainShipping());
        }
        //核算
        hyShippingNoteService.calcCoss(hyShippingNote);
        return Result.OK(hyShippingNote);
    }

    @AutoLog(value = "预支付对账")
    @ApiOperation(value = "预支付对账", notes = "预支付对账")
    @PutMapping(value = "/preCheck")
    @RequiresPermissions("shipping:check")
    @Transactional
    public Result<?> preCheck(@RequestBody HyShippingNote hyShippingNote) {
        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            String orderMode = hyShippingNote.getOrderMode();
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                        ) {
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                    return Result.error("数据错误!");
                }
            }
        }
        HyShippingNote hyShippingNotedDb = hyShippingNoteService.getById(hyShippingNote.getId());
        String prePayStatus = hyShippingNotedDb.getPrePayStatus();
        if (!"1".equals(prePayStatus)) {
            return Result.error("预支付状态错误!");
        }

        BigDecimal goodsWeightLoading = hyShippingNote.getGoodsWeightLoading();
        if (goodsWeightLoading == null) {
            return Result.error("装货量不能为空!");
        }
        if (goodsWeightLoading.compareTo(BigDecimal.ZERO) <= 0) {
            return Result.error("装货量数据错误!");
        }

        BigDecimal preUnitFee = hyShippingNote.getPreUnitFee();
        if (preUnitFee == null) {
            return Result.error("预付运费单价不能为空!");
        }
        if (preUnitFee.compareTo(BigDecimal.ZERO) <= 0) {
            return Result.error("预付运费单价数据错误!");
        }
        if (NumberUtil.isGreaterOrEqual(preUnitFee, hyShippingNote.getShippingUnitPrice())) {
            return Result.error("预付运费单价必须小于运费单价!");
        }


        String preType = hyShippingNote.getPreType();
        BigDecimal preFee = null;
        if ("1".equals(preType)) {
            preFee = preUnitFee.multiply(goodsWeightLoading);
        } else {
            preFee = preUnitFee;
        }
        preFee = preFee.setScale(2, BigDecimal.ROUND_HALF_UP);

        hyShippingNotedDb.setGoodsWeightLoading(goodsWeightLoading);
        hyShippingNotedDb.setPreUnitFee(preUnitFee);
        hyShippingNotedDb.setPreFee(preFee);
        hyShippingNotedDb.setPreType(preType);
        //设置成待支付
        hyShippingNotedDb.setPrePayStatus("4");
        hyShippingNoteService.updateById(hyShippingNotedDb);

        //创建支付订单
        List<HyBill> hyBills = billService.createBills(Collections.singletonList(hyShippingNote), BillTypeEnum.PRE_PAY, null);
        this.hyBillService.saveBatch(hyBills);
        return Result.OK("对账完成!");
    }

    @AutoLog(value = "运单表-对账")
    @ApiOperation(value = "运单表-对账", notes = "运单表-对账")
    @PutMapping(value = "/check")
    @RequiresPermissions("shipping:check")
    @Transactional
    public Result<?> check(@RequestBody HyShippingNote hyShippingNote) {
        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            String orderMode = hyShippingNote.getOrderMode();
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                        ) {
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                    return Result.error("数据错误!");
                }
            }
        }
        HyShippingNote hyShippingNotedDb = hyShippingNoteService.getByIdForUpdate(hyShippingNote.getId());
        if (hyShippingNotedDb == null) {
            return Result.error("运单不存在或已删除!");
        }
        if (!"5".equals(hyShippingNotedDb.getShippingStatus())) {
            return Result.error("运单未签收,不能对账!");
        }

        String imgLoading = hyShippingNote.getImgLoading();
        String imgUnloading = hyShippingNote.getImgUnloading();

        if ("1".equals(settingService.getSettingValueByTag2("usedLoadingImg"))) {
            if (StringUtils.isEmpty(imgLoading)) {
                return Result.error("装货凭证不能为空!");
            }
        }
        if ("1".equals(settingService.getSettingValueByTag2("usedUnLoadingImg"))) {
            if (StringUtils.isEmpty(imgUnloading)) {
                return Result.error("卸货凭证不能为空!");
            }
        }
        //装卸货榜单加水印
        hyShippingNoteService.getWatermarkPic(hyShippingNote, imgLoading, imgUnloading,
                hyShippingNotedDb.getImgLoading(), hyShippingNotedDb.getImgUnloading()
        );

        if ("1".equals(hyShippingNotedDb.getShippingPayStatus()) || "2".equals(hyShippingNotedDb.getShippingPayStatus()) || "8".equals(hyShippingNotedDb.getShippingPayStatus())) {

            //核实前台计算
            HyShippingNote newHyShippingNote = new HyShippingNote();
            BeanUtils.copyProperties(hyShippingNote, newHyShippingNote);
            hyShippingNoteService.calcCoss(newHyShippingNote);
            hyShippingNote.setIzServiceOpenInvoicing(newHyShippingNote.getIzServiceOpenInvoicing());
//			hyShippingNote.setIzInformationFeeOpenInvoicing(newHyShippingNote.getIzInformationFeeOpenInvoicing());
            hyShippingNote.setDriverFee(newHyShippingNote.getDriverFee());
            hyShippingNote.setCustomerFee(newHyShippingNote.getCustomerFee());
            hyShippingNote.setAgentFee(newHyShippingNote.getAgentFee());
            hyShippingNote.setMl(newHyShippingNote.getMl());
            hyShippingNote.setCostServicePercent(newHyShippingNote.getCostServicePercent());
            hyShippingNote.setCustomerPrice(newHyShippingNote.getCustomerPrice());
            hyShippingNote.setCustomerUnitPrice(newHyShippingNote.getCustomerUnitPrice());

            //Added at 2024-05-02 for 对账时如果不点计算直接点对账，需要增加代收人运费重新赋值后的判断
            hyShippingNote.setCarrierFee(newHyShippingNote.getCarrierFee());
            hyShippingNote.setCarrierUnitFee(newHyShippingNote.getCarrierUnitFee());
            //如果是代收人模式，代收人运费不能为0
            String payType = hyShippingNote.getPayType();
            if ("2".equals(payType)) {
                if (hyShippingNote.getCarrierFee().compareTo(BigDecimal.ZERO) <= 0) {
                    log.error("运单[" + hyShippingNote.getShippingNoteNumber() + "]代收人运费金额错误，请确认代收人运费!");
                    return Result.error("代收人运费金额错误，请确认代收人运费!");
                }
            }
            //Added end 2024-05-02

            //亏吨
            if (hyShippingNote.getGoodsWeightLoss().compareTo(newHyShippingNote.getGoodsWeightLoss()) != 0) {
                return Result.error("亏吨核算错误!");
            }
            //亏损金额
            if (hyShippingNote.getCostLoss().compareTo(newHyShippingNote.getCostLoss()) != 0) {
                return Result.error("亏损金额核算错误!");
            }
            //应付金额
            if (hyShippingNote.getCostPay().compareTo(newHyShippingNote.getCostPay()) != 0) {
                return Result.error("应付金额核算错误!");
            }
            // 实际运费金额
            if (hyShippingNote.getCostPayShipping().compareTo(newHyShippingNote.getCostPayShipping()) != 0) {
                return Result.error("实付运费核算错误!");
            }
            //服务费
            if (hyShippingNote.getCostService().compareTo(newHyShippingNote.getCostService()) != 0) {
                return Result.error("服务费核算错误!");
            }
            //合计金额
            if (hyShippingNote.getCostPayTotal().compareTo(newHyShippingNote.getCostPayTotal()) != 0) {
                return Result.error("合计金额核算错误!");
            }
            HyCompanyConfig companyConfig = companyConfigService.getByCompanyId(hyShippingNote.getCompanyId());
            if (companyConfig != null && 1 == companyConfig.getScenePhoto()) {
                String loadingSceneImg = hyShippingNote.getLoadingSceneImg();
                String unloadingSceneImg = hyShippingNote.getUnloadingSceneImg();

                //是否修改装卸货现场图片 ，如修改重新添加水印。
                if (StringUtils.isEmpty(loadingSceneImg)) {
                    return Result.error("装货现场图片不能为空!");
                }
                if (StringUtils.isEmpty(unloadingSceneImg)) {
                    return Result.error("卸货现场图片不能为空!");
                }
                //是否修改装卸货现场图片 ，如修改重新添加水印。
                if (!StringUtils.equals(loadingSceneImg, hyShippingNotedDb.getLoadingSceneImg())) {
                    String waterMarkImg = hyShippingNoteService.buildWaterMarkImg(hyShippingNote, loadingSceneImg, "send");
                    hyShippingNote.setLoadingSceneImg(StringUtils.isNotEmpty(waterMarkImg) ? waterMarkImg : loadingSceneImg);
                }

                if (!StringUtils.equals(unloadingSceneImg, hyShippingNotedDb.getUnloadingSceneImg())) {
                    String waterMarkImg = hyShippingNoteService.buildWaterMarkImg(hyShippingNote, unloadingSceneImg, "receive");
                    hyShippingNote.setUnloadingSceneImg(StringUtils.isNotEmpty(waterMarkImg) ? waterMarkImg : unloadingSceneImg);
                }
            }


            String realName = UserUtil.getLoginUser().getRName();
            hyShippingNote.setDzr(realName);//设置对账人
            hyShippingNote.setShippingPayStatus("2");
            hyShippingNote.setPayDtCheck(new Date());//对账完成时间

            if (hyShippingNotedDb.getShippingUnitPrice() == null) {
                hyShippingNotedDb.setShippingUnitPrice(BigDecimal.ZERO);
            }
            if (hyShippingNotedDb.getLossGoodsUnitPrice() == null) {
                hyShippingNotedDb.setLossGoodsUnitPrice(BigDecimal.ZERO);
            }
            if (hyShippingNotedDb.getLossProportion() == null) {
                hyShippingNotedDb.setLossProportion(BigDecimal.ZERO);
            }
            if (hyShippingNotedDb.getGoodsWeightLoading() == null) {
                hyShippingNotedDb.setGoodsWeightLoading(BigDecimal.ZERO);
            }
            if (hyShippingNotedDb.getGoodsWeightUnloading() == null) {
                hyShippingNotedDb.setGoodsWeightUnloading(BigDecimal.ZERO);
            }
//			if((!StringUtils.equals(hyShippingNotedDb.getShippingType(),hyShippingNote.getShippingType()))
//					||(hyShippingNote.getShippingUnitPrice().compareTo(hyShippingNotedDb.getShippingUnitPrice()) !=0)
//					||( hyShippingNote.getLossGoodsUnitPrice().compareTo(hyShippingNotedDb.getLossGoodsUnitPrice()) !=0)
//					||(!StringUtils.equals(hyShippingNotedDb.getLossType(),hyShippingNote.getLossType()))
//					||( hyShippingNote.getLossProportion().compareTo(hyShippingNotedDb.getLossProportion()) !=0)
//					||( hyShippingNote.getGoodsWeightLoading().compareTo(hyShippingNotedDb.getGoodsWeightLoading()) !=0)
//					||( hyShippingNote.getGoodsWeightUnloading().compareTo(hyShippingNotedDb.getGoodsWeightUnloading()) !=0)
//			){
//				//添加历史记录
//				HyShippingNoteHistory history = new HyShippingNoteHistory();
//				BeanUtils.copyProperties(hyShippingNotedDb, history);
//				history.setShippingId(hyShippingNotedDb.getId());
//				history.setHistoryType("1");
//				history.setId(null);
//				hyShippingNoteHistoryService.save(history);
//			}
            String driverBankId = hyShippingNote.getDriverBankId();
            if (StringUtils.isEmpty(driverBankId)) {
                //检查自动司机提现设置
//				if("1".equals(settingService.getSettingValueByTag2("autotx"))){
//					return  Result.error("请选择司机银行卡");
//				}
                hyShippingNote.setDriverBankId("");//解决null不更新的问题
            } else {
                HyDriverBank driverBank = hyDriverBankService.getById(driverBankId);
                if (driverBank == null) {
                    return Result.error("司机银行卡不存在");
                }
                if (!StringUtils.equals(driverBank.getDriverId(), hyShippingNote.getDriverId())) {
                    return Result.error("司机银行卡信息错误");
                }
            }
            hyShippingNoteService.updateById(hyShippingNote);

            //Modified start at 2024-07-15 for 重构运输节点消息通知功能
            this.applicationEventPublisher.publishEvent(ShippingNoticeEvent.builder()
                    .msgType(MessageTypeEnum.MESSAGE_TYPE_CHECK.getCode())
                    .shippingId(hyShippingNote.getId())
                    .shippingNoteNumber(hyShippingNote.getShippingNoteNumber())
                    .driverId(hyShippingNote.getDriverId())
                    .vehicleId(hyShippingNote.getVehicleId())
                    .loginUser(UserUtil.getLoginUser())
                    .dateTime(new Date())
                    .build());
            //Modified end at 2024-07-15 for 重构运输节点消息通知功能

            return Result.OK("对账完成!");
        } else {
            return Result.error("运单未签收,不能对账!");
        }
    }

    @AutoLog(value = "运单表-批量对账")
    @ApiOperation(value = "运单表-对账", notes = "运单表-对账")
    @PostMapping(value = "/checkBatch")
    @RequiresPermissions("shipping:check")
    @Transactional
    public Result<?> checkBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> shippingids = Arrays.asList(ids.split(","));
        if (shippingids.size() <= 0) {
            return Result.error("ids不能为空!");
        }

        boolean issys = userUtil.isSys();
        HyCustomer customer = userUtil.getCustomer();
        if (!issys) {
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
        }

        List<HyShippingNote> hyShippingNotes = hyShippingNoteService.listByIdsForUpdate(shippingids);
        if (hyShippingNotes == null || hyShippingNotes.size() == 0) {
            return Result.error("运单信息不能为空");
        }
        //检查运单是否创建过，避免重复创建
        List<HyBill> hyBillList = hyBillService.getBillListByShippingIds(shippingids, BillTypeEnum.PAY.value);
        if (hyBillList.size() > 0) {
            return Result.error("所选运单已创建支付订单，请刷新后重试");
        }
        for (HyShippingNote hyShippingNote : hyShippingNotes) {
            if (!issys) {
                String orderMode = hyShippingNote.getOrderMode();
                if ("3".equals(orderMode)) {
                    if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                            && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                            ) {
                        return Result.error("数据错误!");
                    }
                } else {
                    if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                        return Result.error("数据错误!");
                    }
                }
            }

            //Added at 2024-05-02 for 如果是代收人模式，代收人运费不能为0
            String payType = hyShippingNote.getPayType();
            if ("2".equals(payType)) {
                if (hyShippingNote.getCarrierFee().compareTo(BigDecimal.ZERO) <= 0) {
                    log.error("运单[" + hyShippingNote.getShippingNoteNumber() + "]代收人运费金额错误，请确认代收人运费!");
                    return Result.error("运单" + hyShippingNote.getShippingNoteNumber() + "代收人运费金额错误，请确认代收人运费!");
                }
            }
            //Added end 2024-05-02

            if (!"1".equals(hyShippingNote.getIzUsedPayPlan())) {
                if (!"5".equals(hyShippingNote.getShippingStatus())) {
                    return Result.error("运单未签收,不能对账!");
                }
                if ("8".equals(hyShippingNote.getShippingPayStatus())) {
                    return Result.error("包含被驳回的运单,不能批量对账!");
                }
                if (!"1".equals(hyShippingNote.getShippingPayStatus())
                        && !"2".equals(hyShippingNote.getShippingPayStatus())) {
                    return Result.error("运单未签收,不能对账!");
                }
            }


        }
        /**  修改批量对账时不进行批量提交改为手动提交*/
        //String isAut = settingService.getSettingValueByTag2("isshippingnoteAut");
        String realName = UserUtil.getLoginUser().getRName();
        for (HyShippingNote hyShippingNote : hyShippingNotes) {

            if ("1".equals(hyShippingNote.getShippingPayStatus())||"2".equals(hyShippingNote.getShippingPayStatus())||"8".equals(hyShippingNote.getShippingPayStatus())) {
                //核实前台计算
                HyShippingNote newHyShippingNote = new HyShippingNote();
                BeanUtils.copyProperties(hyShippingNote, newHyShippingNote);
                hyShippingNoteService.calcCoss(newHyShippingNote);
                hyShippingNote.setIzServiceOpenInvoicing(newHyShippingNote.getIzServiceOpenInvoicing());
//			hyShippingNote.setIzInformationFeeOpenInvoicing(newHyShippingNote.getIzInformationFeeOpenInvoicing());
                hyShippingNote.setDriverFee(newHyShippingNote.getDriverFee());
                hyShippingNote.setCustomerFee(newHyShippingNote.getCustomerFee());
                hyShippingNote.setAgentFee(newHyShippingNote.getAgentFee());
                hyShippingNote.setMl(newHyShippingNote.getMl());
                hyShippingNote.setCostServicePercent(newHyShippingNote.getCostServicePercent());
                hyShippingNote.setCustomerPrice(newHyShippingNote.getCustomerPrice());
                hyShippingNote.setCustomerUnitPrice(newHyShippingNote.getCustomerUnitPrice());

                //Added at 2024-05-02 for 对账时如果不点计算直接点对账，需要增加代收人运费重新赋值后的判断
                hyShippingNote.setCarrierFee(newHyShippingNote.getCarrierFee());
                hyShippingNote.setCarrierUnitFee(newHyShippingNote.getCarrierUnitFee());
                //如果是代收人模式，代收人运费不能为0
                String payType = hyShippingNote.getPayType();
                if ("2".equals(payType)) {
                    if (hyShippingNote.getCarrierFee().compareTo(BigDecimal.ZERO) <= 0) {
                        log.error("运单[" + hyShippingNote.getShippingNoteNumber() + "]代收人运费金额错误，请确认代收人运费!");
                        return Result.error("代收人运费金额错误，请确认代收人运费!");
                    }
                }
                //Added end 2024-05-02

                //亏吨
                if (hyShippingNote.getGoodsWeightLoss().compareTo(newHyShippingNote.getGoodsWeightLoss()) != 0) {
                    return Result.error("亏吨核算错误!");
                }
                //亏损金额
                if (hyShippingNote.getCostLoss().compareTo(newHyShippingNote.getCostLoss()) != 0) {
                    return Result.error("亏损金额核算错误!");
                }
                //应付金额
                if (hyShippingNote.getCostPay().compareTo(newHyShippingNote.getCostPay()) != 0) {
                    return Result.error("应付金额核算错误!");
                }
                // 实际运费金额
                if (hyShippingNote.getCostPayShipping().compareTo(newHyShippingNote.getCostPayShipping()) != 0) {
                    return Result.error("实付运费核算错误!");
                }
                //服务费
                if (hyShippingNote.getCostService().compareTo(newHyShippingNote.getCostService()) != 0) {
                    return Result.error("服务费核算错误!");
                }
                //合计金额
                if (hyShippingNote.getCostPayTotal().compareTo(newHyShippingNote.getCostPayTotal()) != 0) {
                    return Result.error("合计金额核算错误!");
                }
                HyCompanyConfig companyConfig = companyConfigService.getByCompanyId(hyShippingNote.getCompanyId());
                HyShippingNote hyShippingNotedDb = hyShippingNoteService.getById(hyShippingNote.getId());
                if (companyConfig != null && 1 == companyConfig.getScenePhoto()) {
                    String loadingSceneImg = hyShippingNote.getLoadingSceneImg();
                    String unloadingSceneImg = hyShippingNote.getUnloadingSceneImg();

                    //是否修改装卸货现场图片 ，如修改重新添加水印。
                    if (StringUtils.isEmpty(loadingSceneImg)) {
                        return Result.error("装货现场图片不能为空!");
                    }
                    if (StringUtils.isEmpty(unloadingSceneImg)) {
                        return Result.error("卸货现场图片不能为空!");
                    }
                    //是否修改装卸货现场图片 ，如修改重新添加水印。
                    if (!StringUtils.equals(loadingSceneImg, hyShippingNotedDb.getLoadingSceneImg())) {
                        String waterMarkImg = hyShippingNoteService.buildWaterMarkImg(hyShippingNote, loadingSceneImg, "send");
                        hyShippingNote.setLoadingSceneImg(StringUtils.isNotEmpty(waterMarkImg) ? waterMarkImg : loadingSceneImg);
                    }

                    if (!StringUtils.equals(unloadingSceneImg, hyShippingNotedDb.getUnloadingSceneImg())) {
                        String waterMarkImg = hyShippingNoteService.buildWaterMarkImg(hyShippingNote, unloadingSceneImg, "receive");
                        hyShippingNote.setUnloadingSceneImg(StringUtils.isNotEmpty(waterMarkImg) ? waterMarkImg : unloadingSceneImg);
                    }
                }

                if (hyShippingNotedDb.getShippingUnitPrice() == null) {
                    hyShippingNotedDb.setShippingUnitPrice(BigDecimal.ZERO);
                }
                if (hyShippingNotedDb.getLossGoodsUnitPrice() == null) {
                    hyShippingNotedDb.setLossGoodsUnitPrice(BigDecimal.ZERO);
                }
                if (hyShippingNotedDb.getLossProportion() == null) {
                    hyShippingNotedDb.setLossProportion(BigDecimal.ZERO);
                }
                if (hyShippingNotedDb.getGoodsWeightLoading() == null) {
                    hyShippingNotedDb.setGoodsWeightLoading(BigDecimal.ZERO);
                }
                if (hyShippingNotedDb.getGoodsWeightUnloading() == null) {
                    hyShippingNotedDb.setGoodsWeightUnloading(BigDecimal.ZERO);
                }

                hyShippingNote.setDzr(realName);//设置对账人
                hyShippingNote.setPayDtCheck(new Date());//对账完成时间
                hyShippingNote.setShippingPayStatus("2");
                String driverBankId = hyShippingNote.getDriverBankId();
                if (StringUtils.isEmpty(driverBankId)) {
                    //检查自动司机提现设置
//				if("1".equals(settingService.getSettingValueByTag2("autotx"))){
//					return  Result.error("请选择司机银行卡");
//				}
                    hyShippingNote.setDriverBankId("");//解决null不更新的问题
                } else {
                    HyDriverBank driverBank = hyDriverBankService.getById(driverBankId);
                    if (driverBank == null) {
                        return Result.error("司机银行卡不存在");
                    }
                    if (!StringUtils.equals(driverBank.getDriverId(), hyShippingNote.getDriverId())) {
                        return Result.error("司机银行卡信息错误");
                    }
                }
            }

           /* if ("1".equals(isAut)) {
                //审核
               // hyShippingNote.setShippingPayStatus("3");
              //  hyShippingNote.setPayDtSubmitAut(new Date());//申请审核时间
            } else {
                //直接开始支付
              //  hyShippingNote.setShippingPayStatus("4");
              //  hyShippingNote.setPayDtAut(new Date());//申请支付时间
            }*/

            //Modified start at 2024-07-18 for 重构运输节点消息通知功能
            this.applicationEventPublisher.publishEvent(ShippingNoticeEvent.builder()
                    .msgType(MessageTypeEnum.MESSAGE_TYPE_CHECK.getCode())
                    .shippingId(hyShippingNote.getId())
                    .shippingNoteNumber(hyShippingNote.getShippingNoteNumber())
                    .driverId(hyShippingNote.getDriverId())
                    .vehicleId(hyShippingNote.getVehicleId())
                    .loginUser(UserUtil.getLoginUser())
                    .dateTime(new Date())
                    .build());
            //Modified end at 2024-07-18 for 重构运输节点消息通知功能
        }

        this.hyShippingNoteService.updateBatchById(hyShippingNotes);
       /* //创建支付订单
        List<HyBill> hyBills = billService.createBills(hyShippingNotes, BillTypeEnum.PAY, null);

        //Modified start at 2023-05-10 for 如果导入运单时是待支付状态，在导入时已经生成一条支付记录了，不再重复创建支付单
        List<HyBill> hyFilterBills = new ArrayList<>();
        hyBills.stream().forEach(
                bill -> {
                    int count = hyBillService.count(new LambdaQueryWrapper<HyBill>().eq(HyBill::getShippingId, bill.getShippingId()));
                    if (0 == count) {
                        hyFilterBills.add(bill);
                    } else if (1 == count) {
                        //如果已经存在了，取出id把新生成的对账bill数据更新进去
                        HyBill hyBillDB = hyBillService.getOne(new LambdaQueryWrapper<HyBill>().eq(HyBill::getShippingId, bill.getShippingId()));
                        bill.setId(hyBillDB.getId());
                        hyBillService.updateById(bill);
                        //this.hyBillService.updateStatusByShippingId(bill.getShippingId(), bill.getShippingStatus());
                        log.warn("运单批量对账{}已生成支付记录，不再重复生成{}", bill.getShippingId(), JSONUtil.toJsonStr(bill));
                    } else {
                        log.error("运单批量对账失败,有运单存在多条对账记录， {}", JSONUtil.toJsonStr(bill));
                        HyShippingNote hyShippingNote = this.hyShippingNoteService.getById(bill.getShippingId());
                        throw new JeecgBootException("批量对账失败,运单" + hyShippingNote.getShippingNoteNumber() + "存在多条对账记录。");
                    }
                }
        );*/
        //Modified end

        // hyBillService.saveBatch(hyFilterBills);

        return Result.OK("批量对账成功!");
    }

    @AutoLog(value = "运单表-批量修改运费")
    @ApiOperation(value = "运单表-批量修改运费", notes = "运单表-批量修改运费")
    @PostMapping(value = "/batchUpdatePrice")
    public Result batchUpdatePrice(@RequestBody JSONObject jsonObject) {
        //TODO 这是甲一临时提的需求，先不做，等确定后再补充
        log.info("批量修改运费：{}", jsonObject);
        return Result.OK("操作成功");
    }

    @AutoLog(value = "运单表-撤销")
    @ApiOperation(value = "运单表-撤销", notes = "运单表-撤销")
    @PutMapping(value = "/chexiao")
    @RequiresPermissions("shipping:chexiao")
    @Transactional
    public Result<?> chexiao(@RequestParam(name = "id", required = true) String id,
                             @RequestParam(name = "cancelReason", required = true) String cancelReason) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getByIdForUpdate(id);
        if (hyShippingNote == null) {
            return Result.error("该运单不存在");
        }
        if (StringUtils.isBlank(cancelReason)) {
            return Result.error("该运单撤销原因不能为空");
        }


        String shippingPayStatus = hyShippingNote.getShippingPayStatus();
        if ("5".equals(shippingPayStatus)) {
            return Result.error("已申请支付,不撤销");
        }
        if ("6".equals(shippingPayStatus)) {
            return Result.error("已支付完成,不能撤销");
        }
        if ("7".equals(shippingPayStatus)) {
            return Result.error("已申请支付,不能撤销");
        }

        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            String orderMode = hyShippingNote.getOrderMode();
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                        ) {
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                    return Result.error("数据错误!");
                }
            }
        }

        hyShippingNote.setCancelReason(cancelReason);
        hyShippingNote.setHistoryShippingStatus(hyShippingNote.getShippingStatus()); //记录历史状态
        hyShippingNote.setShippingStatus(ShippingStatus.已作废.getValue());
        hyShippingNote.setExamineDate(new Date()); //撤销时间
        hyShippingNoteService.updateById(hyShippingNote);

//        if ("1".equals(hyShippingNote.getAlctIdentification())) {
        //取消运单订阅消息
        //GenMqUtil.sendMsg(EnumGenHandler.SHIPPING_CANCEL, "", hyShippingNote);
        //publisherRedisMessageService.publisherRedisMessage(RedisChannelEnum.SHIPPING_CANCEL, hyShippingNote);
//        }

//        //如果绑定了智运宝设备要终止围栏
//        if (StrUtil.isNotEmpty(hyShippingNote.getVehicleDevice())) {
//            this.zybService.cancelShippingFence(hyShippingNote.getShippingNoteNumber());
//        }

        String izUsedGas = hyShippingNote.getIzUsedGas();
        if ("1".equals(izUsedGas) || "3".equals(izUsedGas)) {
            //回收油气（万金油）
            gasService.backMsg(hyShippingNote);
        }
        return Result.OK("撤销成功!");
    }

    @AutoLog(value = "运单表-撤销恢复")
    @ApiOperation(value = "运单表-撤销恢复", notes = "运单表-撤销恢复")
    @PutMapping(value = "/resume")
    @RequiresPermissions("shipping:chexiao")
    @Transactional
    public Result<?> resume(@RequestParam(name = "id", required = true) String id) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getByIdForUpdate(id);
        if (hyShippingNote == null) {
            return Result.error("该运单不存在");
        }
        if (!"8".equals(hyShippingNote.getShippingStatus())) {
            return Result.error("不是撤销的运单，不能恢复此运单");
        }

        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            String orderMode = hyShippingNote.getOrderMode();
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                        ) {
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                    return Result.error("数据错误!");
                }
            }
        }

        //todo 重新分配油气
        String shippingStatus = hyShippingNote.getHistoryShippingStatus();//获取撤销前状态
        hyShippingNote.setShippingStatus(shippingStatus); //恢复之前的状态
        hyShippingNoteService.updateById(hyShippingNote);
        return Result.OK("操作成功!");
    }

//endregion

    //region 审核
    @AutoLog(value = "运单表-提交审核")
    @ApiOperation(value = "运单表-提交审核", notes = "运单表-提交审核")
    @PutMapping(value = "/submitAut")
    @RequiresPermissions("shipping:submitAut")
    @Transactional
    public Result<?> submitAut(@RequestParam(name = "id", required = true) String id) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getByIdForUpdate(id);
        if (hyShippingNote == null) {
            return Result.error("该运单不存在");
        }
        if (!"2".equals(hyShippingNote.getShippingPayStatus())) {
            return Result.error("未对账完成,不能提交审核!");
        }

        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            String orderMode = hyShippingNote.getOrderMode();
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                        ) {
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                    return Result.error("数据错误!");
                }
            }

        }
        //是否需要审核
        String isAut = settingService.getSettingValueByTag2("isshippingnoteAut");
        if ("1".equals(isAut)) {
            //审核
            hyShippingNote.setShippingPayStatus("3");
            hyShippingNote.setPayDtSubmitAut(new Date());//申请审核时间
        } else {
            //直接开始支付
            hyShippingNote.setShippingPayStatus("4");
            hyShippingNote.setPayDtAut(new Date());//申请支付时间
        }
        hyShippingNoteService.updateById(hyShippingNote);

        //创建支付订单
        //HyBill hyBill = billService.createBill(hyShippingNote, BillTypeEnum.PAY, null, "3");
        HyBill hyBill = billService.createBill(hyShippingNote, BillTypeEnum.PAY, null, isAut);

        //Modified start 如果已经生成一条对账记录了，不再重复创建对账单
        int count = hyBillService.count(new LambdaQueryWrapper<HyBill>().eq(HyBill::getShippingId, hyShippingNote.getId()).eq(HyBill::getBillType, BillTypeEnum.PAY.value));
        if (0 == count) {
            hyBillService.save(hyBill);
        } else if (1 == count) {
            //如果已经存在了，取出id把新生成的对账bill数据更新进去
            HyBill hyBillDB = hyBillService.getOne(new LambdaQueryWrapper<HyBill>().eq(HyBill::getShippingId, hyShippingNote.getId()).eq(HyBill::getBillType, BillTypeEnum.PAY.value));
            hyBill.setId(hyBillDB.getId());
            hyBillService.updateById(hyBill);
            log.warn("运单提交审核{} - {}已生成支付记录，不再重复生成", hyShippingNote.getId(), hyShippingNote.getShippingNoteNumber());
        } else {
            return Result.error("提交失败,该运单存在多条对账记录");
        }
        //Modified end

        //Added start at 2023-12-26 for 辽宁税务上报时在提交对账的过程中更新运费
        if ("1".equals(hyShippingNote.getAlctIdentification())) {
            Result r = this.shippingNoteApiAlct56Service.updatePriceAndContract(hyShippingNote);
            if (!r.getCode().equals(CommonConstant.SC_OK_200)) {
                throw new JeecgBootException(r.getMessage());
            }
        }
        //Added end at 2023-12-26

        //Added start at 2024-04-11 for 提交对账时如果是安徽监管上报运单2
        String realtimeUpload = HyCfgUtil.getCfgItem2("anhui_report","realtime_upload");
        if (StrUtil.isNotEmpty(realtimeUpload)) {
            HyCompanyConfig companyConfig = this.companyConfigService.getByCompanyId(hyShippingNote.getCompanyId());
            if (companyConfig.getReportPlatformType().equals(ReportPlatformEnum.REPORT_PLATFORM_AH.getCode())) {
                log.info("发送异步事件，上报实时运单2 {}", hyShippingNote.getShippingNoteNumber());
                this.applicationEventPublisher.publishEvent(AhRealtimeReportEvent.builder()
                        .shippingId(hyShippingNote.getId())
                        .ahRealtimeType(AhRealtimeEnum.AH_REALTIME_REPORT_STEP2)
                        .build()
                );
            }
        }
        //Added end at 2024-04-11 for 提交对账时如果是安徽监管上报运单2

        return Result.OK("提交成功!");
    }


    @AutoLog(value = "运单表-批量提交审核")
    @ApiOperation(value = "运单表-批量提交审核", notes = "运单表-批量提交审核")
    @PostMapping(value = "/submitAutBatch")
    @RequiresPermissions("shipping:submitAut")
    @Transactional
    public Result<?> submitAutBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> shippingids = Arrays.asList(ids.split(","));
        if (shippingids.size() <= 0) {
            return Result.error("ids不能为空!");
        }
        boolean issys = userUtil.isSys();
        HyCustomer customer = userUtil.getCustomer();
        if (!issys) {
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
        }
        List<HyShippingNote> hyShippingNotes = hyShippingNoteService.listByIdsForUpdate(shippingids);
        if (hyShippingNotes == null || hyShippingNotes.size() == 0) {
            return Result.error("运单信息不能为空");
        }
        List<HyBill> hyBillList = hyBillService.getBillListByShippingIds(shippingids, BillTypeEnum.PAY.value);
        if (hyBillList.size() > 0) {
            return Result.error("所选运单已创建支付订单，请刷新后重试");
        }
        //是否需要审核
        String isAut = settingService.getSettingValueByTag2("isshippingnoteAut");
        for (HyShippingNote hyShippingNote : hyShippingNotes) {
            if (!"2".equals(hyShippingNote.getShippingPayStatus())) {
                return Result.error("未对账完成,不能提交审核!");
            }
            if (!issys) {
                String orderMode = hyShippingNote.getOrderMode();
                if ("3".equals(orderMode)) {
                    if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                            && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                            ) {
                        return Result.error("数据错误!");
                    }
                } else {
                    if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                        return Result.error("数据错误!");
                    }
                }
            }
            if ("1".equals(isAut)) {
                //审核
                hyShippingNote.setShippingPayStatus("3");
                hyShippingNote.setPayDtSubmitAut(new Date());//申请审核时间
            } else {
                //直接开始支付
                hyShippingNote.setShippingPayStatus("4");
                hyShippingNote.setPayDtAut(new Date());//申请支付时间
            }

            //Added start at 2023-12-26 for 辽宁税务上报时在提交对账的过程中更新运费
            if ("1".equals(hyShippingNote.getAlctIdentification())) {
                Result r = this.shippingNoteApiAlct56Service.updatePriceAndContract(hyShippingNote);
                if (!r.getCode().equals(CommonConstant.SC_OK_200)) {
                    throw new JeecgBootException(r.getMessage());
                }
            }
            //Added end at 2023-12-26

            //Added start at 2024-04-11 for 提交对账时如果是安徽监管上报运单2
            String realtimeUpload = HyCfgUtil.getCfgItem2("anhui_report","realtime_upload");
            if (StrUtil.isNotEmpty(realtimeUpload)) {
                HyCompanyConfig companyConfig = this.companyConfigService.getByCompanyId(hyShippingNote.getCompanyId());
                if (companyConfig.getReportPlatformType().equals(ReportPlatformEnum.REPORT_PLATFORM_AH.getCode())) {
                    log.info("发送异步事件，上报实时运单2 {}", hyShippingNote.getShippingNoteNumber());
                    this.applicationEventPublisher.publishEvent(AhRealtimeReportEvent.builder()
                            .shippingId(hyShippingNote.getId())
                            .ahRealtimeType(AhRealtimeEnum.AH_REALTIME_REPORT_STEP2)
                            .build()
                    );
                }
            }
            //Added end at 2024-04-11 for 提交对账时如果是安徽监管上报运单2
        }
        this.hyShippingNoteService.updateBatchById(hyShippingNotes);
        //创建支付订单
        List<HyBill> hyBills = billService.createBills(hyShippingNotes, BillTypeEnum.PAY, null);
        hyBillService.saveBatch(hyBills);
        return Result.OK("批量提交成功!");
    }

    @AutoLog(value = "运单表-业务审核")
    @ApiOperation(value = "运单表-业务审核", notes = "运单表-业务审核")
    @PutMapping(value = "/BusinessReview")
    public Result<?> BusinessReview(@RequestParam(name = "id", required = true) String id) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getById(id);
        if (hyShippingNote == null) {
            return Result.error("该运单不存在");
        }

        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer != null) {
                String orderMode = hyShippingNote.getOrderMode();
                if ("3".equals(orderMode)) {
                    if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                            && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                            ) {
                        return Result.error("数据错误!");
                    }
                } else {
                    if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                        return Result.error("数据错误!");
                    }
                }
            }
        }


        String realName = UserUtil.getLoginUser().getRName();
        hyShippingNote.setShrr(realName);//设置审核人

//		hyShippingNote.setShippingPayStatus("4");
//		hyShippingNote.setPayDtAut(new Date());//审核完成时间
        hyShippingNoteService.updateById(hyShippingNote);
        return Result.OK("审核成功!");
    }


    @AutoLog(value = "运单表-审核")
    @ApiOperation(value = "运单表-审核", notes = "运单表-审核")
    @PutMapping(value = "/aut")
    @RequiresPermissions("shipping:sysAut")
    public Result<?> aut(@RequestParam(name = "id", required = true) String id) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getById(id);
        if (hyShippingNote == null) {
            return Result.error("该运单不存在");
        }

        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer != null) {
                String orderMode = hyShippingNote.getOrderMode();
                if ("3".equals(orderMode)) {
                    if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                            && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                            ) {
                        return Result.error("数据错误!");
                    }
                } else {
                    if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                        return Result.error("数据错误!");
                    }
                }
            }
        }

        if (!"3".equals(hyShippingNote.getShippingPayStatus())) {
            return Result.error("未对账完成,不能审核!");
        }

        String realName = UserUtil.getLoginUser().getRName();
        hyShippingNote.setShrr(realName);//设置审核人
        hyShippingNote.setShippingPayStatus("4");
        hyShippingNote.setPayDtAut(new Date());//审核完成时间
        hyShippingNoteService.updateById(hyShippingNote);
        return Result.OK("审核成功!");
    }

    @AutoLog(value = "运单表-财务审核")
    @ApiOperation(value = "运单表-财务审核", notes = "运单表-财务审核")
    @PutMapping(value = "/examine")
    public Result<?> examine(@RequestBody HyShippingNote hyShippingNoteInfo) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getById(hyShippingNoteInfo.getId());
        if (hyShippingNote == null) {
            return Result.error("该运单不存在");
        }
		/*if(!"4".equals(hyShippingNoteInfo.getShippingPayStatus()) && !"8".equals(hyShippingNoteInfo.getShippingPayStatus())){
			return Result.error("该运单审核状态不正确");
		}*/

        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer != null) {
                String orderMode = hyShippingNote.getOrderMode();
                if ("3".equals(orderMode)) {
                    if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                            && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                            ) {
                        return Result.error("数据错误!");
                    }
                } else {
                    if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                        return Result.error("数据错误!");
                    }
                }
            }
        }

		/*if (!"3".equals(hyShippingNote.getShippingPayStatus())) {
			return Result.error("未对账完成,不能审核!");
		}*/


//		hyShippingNote.setShippingPayStatus(hyShippingNoteInfo.getShippingPayStatus()) ;
        hyShippingNote.setExamineRemark(hyShippingNoteInfo.getExamineRemark());
        String realName = UserUtil.getLoginUser().getRName();
        hyShippingNote.setShrr(realName);//设置审核人
        //审核通过
        if (hyShippingNoteInfo.getShippingPayStatus().equals("88")) {
            if (hyShippingNote.getShippingPayStatus().equals("3")) {
                hyShippingNote.setShippingPayStatus("4");
            }

        }
        //驳回
        if (hyShippingNoteInfo.getShippingPayStatus().equals("99")) {
            if (hyShippingNote.getShippingPayStatus().equals("3")) {
                hyShippingNote.setShippingPayStatus("1");
            }

        }


        hyShippingNote.setPayDtAut(new Date());//审核完成时间
        hyShippingNoteService.updateById(hyShippingNote);
        return Result.OK("审核成功!");
    }

    @AutoLog(value = "运单表-业务审核")
    @ApiOperation(value = "运单表-业务审核", notes = "运单表-业务审核")
    @PutMapping(value = "/examineyewu")
    public Result<?> examineyewu(@RequestBody HyShippingNote hyShippingNoteInfo) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getById(hyShippingNoteInfo.getId());
        if (hyShippingNote == null) {
            return Result.error("该运单不存在");
        }
		/*if(!"4".equals(hyShippingNoteInfo.getShippingPayStatus()) && !"8".equals(hyShippingNoteInfo.getShippingPayStatus())){
			return Result.error("该运单审核状态不正确");
		}*/

        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer != null) {
                String orderMode = hyShippingNote.getOrderMode();
                if ("3".equals(orderMode)) {
                    if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                            && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                            ) {
                        return Result.error("数据错误!");
                    }
                } else {
                    if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                        return Result.error("数据错误!");
                    }
                }
            }
        }

		/*if (!"3".equals(hyShippingNote.getShippingPayStatus())) {
			return Result.error("未对账完成,不能审核!");
		}*/


//		hyShippingNote.setShippingPayStatus(hyShippingNoteInfo.getShippingPayStatus()) ;
        hyShippingNote.setExamineRemark(hyShippingNoteInfo.getExamineRemark());
        String realName = UserUtil.getLoginUser().getRName();
        hyShippingNote.setShrr(realName);//设置审核人
        //审核通过
        if (hyShippingNoteInfo.getShippingPayStatus().equals("88")) {
            hyShippingNote.setShippingPayStatus("1"); //申请对账
            hyShippingNote.setPayDtSubmitCheck(new Date());//申请对账时间
        }
        //驳回
        if (hyShippingNoteInfo.getShippingPayStatus().equals("99")) {
            hyShippingNote.setShippingPayStatus("10");
        }


        hyShippingNote.setPayDtAut(new Date());//审核完成时间
        hyShippingNoteService.updateById(hyShippingNote);
        return Result.OK("审核成功!");
    }

    @AutoLog(value = "运单表-货主提交业务审核失败")
    @ApiOperation(value = "运单表-货主提交业务审核失败", notes = "运单表-货主提交业务审核失败")
    @PutMapping(value = "/examineyewuno")
    public Result<?> examineyewuno(@RequestBody HyShippingNote hyShippingNoteInfo) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getById(hyShippingNoteInfo.getId());
        if (hyShippingNote == null) {
            return Result.error("该运单不存在");
        }
		/*if(!"4".equals(hyShippingNoteInfo.getShippingPayStatus()) && !"8".equals(hyShippingNoteInfo.getShippingPayStatus())){
			return Result.error("该运单审核状态不正确");
		}*/

        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer != null) {
                String orderMode = hyShippingNote.getOrderMode();
                if ("3".equals(orderMode)) {
                    if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                            && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                            ) {
                        return Result.error("数据错误!");
                    }
                } else {
                    if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                        return Result.error("数据错误!");
                    }
                }
            }
        }

		/*if (!"3".equals(hyShippingNote.getShippingPayStatus())) {
			return Result.error("未对账完成,不能审核!");
		}*/


//		hyShippingNote.setShippingPayStatus(hyShippingNoteInfo.getShippingPayStatus()) ;
        hyShippingNote.setExamineRemark(hyShippingNoteInfo.getExamineRemark());
        String realName = UserUtil.getLoginUser().getRName();
        hyShippingNote.setShrr(realName);//设置审核人
        //审核通过
        if (hyShippingNoteInfo.getShippingPayStatus().equals("88")) {
            hyShippingNote.setShippingPayStatus("9"); //业务审核
        }

        hyShippingNote.setPayDtAut(new Date());//审核完成时间
        hyShippingNoteService.updateById(hyShippingNote);
        return Result.OK("审核成功!");
    }


    @AutoLog(value = "运单表-批量审核")
    @ApiOperation(value = "运单表-批量审核", notes = "运单表-批量审核")
    @PostMapping(value = "/autBatch")
    @RequiresPermissions("shipping:batchSysAut")
    public Result<?> autBatch(@RequestParam(name = "ids", required = true) String ids) {
        String realName = UserUtil.getLoginUser().getRName();
        List<HyShippingNote> hyShippingNotes = hyShippingNoteService.listByIds(Arrays.asList(ids.split(",")));
        HyCustomer customer = userUtil.getCustomer();
        for (HyShippingNote hyShippingNote : hyShippingNotes) {
            if (!"3".equals(hyShippingNote.getShippingPayStatus())) {
                return Result.error("未对账完成,不能审核!");
            }
            if (customer != null) {
                String orderMode = hyShippingNote.getOrderMode();
                if ("3".equals(orderMode)) {
                    if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                            && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                            ) {
                        return Result.error("数据错误!");
                    }
                } else {
                    if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                        return Result.error("数据错误!");
                    }
                }
            }
            hyShippingNote.setShippingPayStatus("4");
            hyShippingNote.setShrr(realName);//设置审核人
            hyShippingNote.setPayDtAut(new Date()); //审核完成时间
        }
        this.hyShippingNoteService.updateBatchById(hyShippingNotes);
        return Result.OK("批量审核成功!");
    }

    @AutoLog(value = "运单表-驳回")
    @ApiOperation(value = "运单表-驳回", notes = "运单表-驳回")
    @PutMapping(value = "/unaut")
    @RequiresPermissions("shipping:unaut")
    @Transactional
    public Result<?> unaut(@RequestParam(name = "id", required = true) String id) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getByIdForUpdate(id);
        if (hyShippingNote == null) {
            return Result.error("该运单不存在");
        }
        if (!userUtil.isSys()) {
            HyCustomer customer = userUtil.getCustomer();
            if (customer == null) {
                return Result.error("货主信息不存在!");
            }
            String orderMode = hyShippingNote.getOrderMode();
            if ("3".equals(orderMode)) {
                if (!StringUtils.equals(hyShippingNote.getAgentId(), customer.getId())
                        && !StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())
                        ) {
                    return Result.error("数据错误!");
                }
            } else {
                if (!StringUtils.equals(hyShippingNote.getCustomerId(), customer.getId())) {
                    return Result.error("数据错误!");
                }
            }
        }
        /*if (hyShippingNote.getOrderMode().equals("4")) {
            HyOrder order = hyOrderService.getById(hyShippingNote.getOrderId());
            hyShippingNote.setCustomerPrice(order.getCustomerPrice());
        }*/
        //支付类型是预付进行驳回
        if (PayConstants.PAY_TYPE.BY_PREPAY.equalsIgnoreCase(hyShippingNote.getPayType()) &&
                PayConstants.PREPAY_ORDER_STATUS.COMPLETE_APPROVAL.equals(hyShippingNote.getPrePayStatus())) {
            //删除 billType=6的支付订单
            hyBillService.deleteBillByShippNoteId(hyShippingNote.getId(), BillTypeEnum.PRE_PAY);
            hyShippingNoteService.lambdaUpdate()
                    .set(HyShippingNote::getPrePayStatus, PayConstants.PREPAY_ORDER_STATUS.PENDING_APPROVAL)
                    .eq(HyShippingNote::getId, hyShippingNote.getId())
                    .update();
            return Result.OK("驳回成功!");
        } else {
            if ("3".equals(hyShippingNote.getShippingPayStatus()) || "4".equals(hyShippingNote.getShippingPayStatus())) {
                hyShippingNote.setShippingPayStatus("8");
                //删除 billType=1的支付订单
                hyBillService.deleteBillByShippNoteId(hyShippingNote.getId(), BillTypeEnum.PAY);
                hyShippingNoteService.updateById(hyShippingNote);
                return Result.OK("驳回成功!");
            }
        }

        return Result.error("不能驳回!");
    }
    //endregion

    //region 轨迹
    //TODO 智运宝获取轨迹
    @ApiOperation(value = "运单轨迹-通过车牌时间查询", notes = "运单轨迹-通过车牌时间查询")
    @GetMapping(value = "/getZybShippingTrack")
    public Result getZybShippingTrack(@RequestParam(name = "shippingId", required = true) String shippingId) {

        HyShippingNote hyShippingNote = this.hyShippingNoteService.getById(shippingId);
        if (null == hyShippingNote) {
            return Result.error("运单信息查找失败");
        }

        WaybillRouteVO waybillRouteVO = this.waybillRouteService.getZybShippingTrack(hyShippingNote.getZybShippingNumber());
        if (waybillRouteVO != null) {
            return Result.OK(
                    JSONObject.parseObject(JSONObject.toJSONString(waybillRouteVO))
            );
        }

        return Result.error("该车辆运单轨迹信息查询失败！");
    }


    @AutoLog(value = "运单轨迹-通过车牌时间查询")
    @ApiOperation(value = "运单轨迹-通过车牌时间查询", notes = "运单轨迹-通过车牌时间查询")
    @GetMapping(value = "/waybillRoute")
    @RequiresPermissions("shipping:track")
    public Result<?> getWaybillRoute(@RequestParam(name = "vehicleNo", required = true) String vehicleNo,
                                     @RequestParam(name = "startTime", required = true) String startTime,
                                     @RequestParam(name = "endTime", required = true) String endTime,
                                     @RequestParam(name = "parkMins", required = false, defaultValue = "0") String parkMins,
                                     @RequestParam(name = "shippingNoteNumber", required = false) String shippingNoteNumber) {
        if (StringUtils.isEmpty(vehicleNo)) {
            return Result.error("车牌号不允许为空!");
        }
        if (StringUtils.isEmpty(startTime)) {
            return Result.error("开始时间不允许为空!");
        }
        if (StringUtils.isEmpty(endTime)) {
            return Result.error("结束时间不允许为空!");
        }
        Date startTimeDate = DateUtils.stringToDateTime(startTime);
        Date endTimeDate = DateUtils.stringToDateTime(endTime);

        if (!endTimeDate.after(startTimeDate)) {
            return Result.error("结束时间不能在开始时间之前！");
        }

        //如果开启了历史轨迹并且保存过轨迹，就调用已经保存的轨迹
        if (StrUtil.isNotEmpty(shippingNoteNumber) && HyCfgUtil.isUsed2("history_trace")) {

            //中交轨迹只能查询6个月的，超出6个月的可以尝试读取本地轨迹记录
            Integer second = DateUtils.getDifferentDaysByMillisecond(startTimeDate, new Date());
            if (second > (3600 * 24 * 180)) {
                WaybillRouteVO waybillRouteVO = waybillRouteService.getWaybillByFile(shippingNoteNumber);
                if (null != waybillRouteVO) {
                    return Result.OK(JSONObject.parseObject(JSONObject.toJSONString(waybillRouteVO)));
                } else {
                    return Result.error("运单历史轨迹信息查询失败");
                }
            }
        }

        startTime = DateUtils.dateTimeToString(startTimeDate);
        endTime = DateUtils.dateTimeToString(endTimeDate);
        parkMins = StringUtils.isBlank(parkMins) ? "0" : parkMins;
        WaybillRouteVO waybillRouteVO = waybillRouteService.getRouterPath(vehicleNo, startTime, endTime, parkMins);
        if (waybillRouteVO != null) {
            if (StrUtil.isNotEmpty(shippingNoteNumber)) {
                //保存公里数
                this.hyShippingNoteService.update(new LambdaUpdateWrapper<HyShippingNote>()
                        .eq(HyShippingNote::getShippingNoteNumber, shippingNoteNumber)
                        .set(HyShippingNote::getTransportationDistance, waybillRouteVO.getMileage()));

                //发送异步事件，保存历史轨迹
                if (HyCfgUtil.isUsed2("history_trace")) {
                    log.info("发送异步事件，保存历史轨迹 {} {}", shippingNoteNumber, vehicleNo);
                    this.applicationEventPublisher.publishEvent(HistoryTraceEvent.builder()
                            .shippingNoteNumber(shippingNoteNumber)
                            .vehicleNumber(vehicleNo)
                            .startTime(startTime)
                            .endTime(endTime)
                            .mileage(waybillRouteVO.getMileage())
                            .waybillRouteVO(waybillRouteVO)
                            .build()
                    );
                }
            }

            return Result.OK(
                    JSONObject.parseObject(JSONObject.toJSONString(waybillRouteVO))
            );
        }
        return Result.error("该车辆运单轨迹信息查询失败！");
    }

    @ApiOperation(value = "运单轨迹-通过车牌时间查询", notes = "运单轨迹-通过车牌时间查询")
    @GetMapping(value = "/waybillRoute2")
    @RequiresPermissions("shipping:track")
    public Result<?> getWaybillRoute(@RequestParam(name = "id", required = true) String id,
                                     @RequestParam(name = "parkMins", required = false, defaultValue = "0") String parkMins) {


        HyShippingNote shippingNote = hyShippingNoteService.getById(id);

        Date startTimeDate = shippingNote.getStatusDtLoading();
        Date endTimeDate = shippingNote.getStatusDtUnloading();
        //		 Integer days = DateUtils.differentDaysByMillisecond(startTimeDate,  endTimeDate);
        //		 if(days>1){
        //			 return Result.error("查询时间不能大于24小时！");
        //		 }
        // startTimeDate.before(endTimeDate)
        if (ObjectUtil.isEmpty(startTimeDate)) {
            return Result.error("运单" + shippingNote.getShippingNoteNumber() + "轨迹查询失败");
        }

        if (ObjectUtil.isEmpty(endTimeDate)) {
            endTimeDate = new Date();
        }

        if (!endTimeDate.after(startTimeDate)) {
            return Result.error("结束时间不能在开始时间之前！");
        }
//		Integer second = DateUtils.getDifferentDaysByMillisecond(startTimeDate, endTimeDate);
//		int days = 1;
//		if (second > 86400) {
//			double diff = (double) second / 86400;
//			days = (int) Math.ceil(diff);
//		}
//		if(days > 7){
//			return Result.error("查询时间段不能大于7天！");
//		}

        HyVehicle vehicle = hyVehicleService.getById(shippingNote.getVehicleId());
        String startTime = DateUtils.dateTimeToString(startTimeDate);
        String endTime = DateUtils.dateTimeToString(endTimeDate);
        parkMins = StringUtils.isBlank(parkMins) ? "0" : parkMins;
        WaybillRouteVO waybillRouteVO = waybillRouteService.getRouterPath(vehicle.getVehicleNumber(), startTime, endTime, parkMins);
        if (waybillRouteVO != null) {
            return Result.OK(
                    JSONObject.parseObject(JSONObject.toJSONString(waybillRouteVO))
            );
        }
        return Result.error("该车辆运单轨迹信息查询失败！");
    }

    @ApiOperation(value = "运单轨迹-通过车牌时间查询", notes = "运单轨迹-通过车牌时间查询")
    @GetMapping(value = "/waybillRouteApp")
    public Result<?> getWaybillRouteApp(@RequestParam(name = "vehicleNo", required = true) String vehicleNo,
                                        @RequestParam(name = "startTime", required = true) String startTime,
                                        @RequestParam(name = "endTime", required = true) String endTime) {
        if (StringUtils.isEmpty(vehicleNo)) {
            return Result.error("车牌号不允许为空!");
        }
        if (StringUtils.isEmpty(startTime)) {
            return Result.error("开始时间不允许为空!");
        }
        if (StringUtils.isEmpty(endTime)) {
            return Result.error("结束时间不允许为空!");
        }
        Date startTimeDate = DateUtils.stringToDateTime(startTime);
        Date endTimeDate = DateUtils.stringToDateTime(endTime);
        //		 Integer days = DateUtils.differentDaysByMillisecond(startTimeDate,  endTimeDate);
        //		 if(days>1){
        //			 return Result.error("查询时间不能大于24小时！");
        //		 }
        // startTimeDate.before(endTimeDate)
        if (!endTimeDate.after(startTimeDate)) {
            return Result.error("结束时间不能在开始时间之前！");
        }
//		int second = DateUtils.getDifferentDaysByMillisecond(startTimeDate, endTimeDate);
//		int days = 1;
//
//		if (second > 86400) {
//			BigDecimal diff = new BigDecimal(second*1000).divide(new BigDecimal(86400000),7, BigDecimal.ROUND_HALF_UP);
//			days = (int) Math.ceil(diff.doubleValue());
//		}
//
//		if(days > 7){
//			return Result.error("查询时间段不能大于7天！");
//		}

        HyVehicle hyVehicle = this.hyVehicleService.getHyVehicleByVehicleNumber(vehicleNo);

        startTime = DateUtils.dateTimeToString(startTimeDate);
        endTime = DateUtils.dateTimeToString(endTimeDate);
        String vehicleColor = StringUtils.isNotEmpty(hyVehicle.getVehiclePlateColorCode()) ? hyVehicle.getVehiclePlateColorCode() : "2";
        WaybillRouteVO waybillRouteVO = waybillRouteService.getWaybillRoute(vehicleNo, vehicleColor, startTime, endTime, "GCJ02");
        if (waybillRouteVO != null) {
            return Result.OK(
                    JSONObject.parseObject(JSONObject.toJSONString(waybillRouteVO))
            );
        }
        return Result.error("该车辆运单轨迹信息查询失败！");
    }

    //	@AutoLog(value = "运单轨迹-模拟轨迹")
    @ApiOperation(value = "运单轨迹-模拟轨迹", notes = "运单轨迹-模拟轨迹")
    @GetMapping(value = "/simulateTrackQuery")
    @RequiresPermissions("shipping:track")
    public Result<?> getSimulateTrackQuery(@RequestParam(name = "vehicleNo", required = true) String vehicleNo,
                                           @RequestParam(name = "shippingNoteNumber", required = true) String shippingNoteNumber
    ) {
        if (StringUtils.isEmpty(vehicleNo)) {
            return Result.error("车牌号不允许为空!");
        }
        if (StringUtils.isEmpty(shippingNoteNumber)) {
            return Result.error("运单号号不允许为空!");
        }

        HyShippingNote shippingNote = hyShippingNoteService.queryByShippingNoteNumber(shippingNoteNumber);
        if (shippingNote == null) {
            return Result.error("运单信息不允许为空!");
        }
        WaybillRouteVO waybillRouteVO = shippingNoteAmapService.getSimulateTrackQuery(shippingNote);
        if (waybillRouteVO != null) {
            return Result.OK(
                    JSONObject.parseObject(JSONObject.toJSONString(waybillRouteVO))
            );
        }
        return Result.error("该运单模拟轨迹失败！");
    }

    //	@AutoLog(value = "运单轨迹-模拟轨迹")
    @ApiOperation(value = "运单轨迹-模拟轨迹", notes = "运单轨迹-模拟轨迹")
    @GetMapping(value = "/getSimulateTrackQueryOrder")
    @RequiresPermissions("shipping:track")
    public Result<?> getSimulateTrackQueryOrder(@RequestParam(name = "orderId", required = true) String orderId) {

        if (StringUtils.isEmpty(orderId)) {
            return Result.error("货源号不允许为空!");
        }

        HyOrder order = hyOrderService.getById(orderId);
        if (order == null) {
            return Result.error("货源信息不允许为空!");
        }

        WaybillRouteVO waybillRouteVO = shippingNoteAmapService.getSimulateTrackQueryOrder(order);
        if (waybillRouteVO != null) {
            return Result.OK(JSONUtil.toJsonStr(waybillRouteVO));
        }
        return Result.error("该运单模拟轨迹失败！");
    }

    @ApiOperation(value = "运单实时轨迹-通过车牌查询", notes = "运单实时轨迹-通过车牌查询")
    @GetMapping(value = "/getRealLocation")
    @RequiresPermissions("shipping:track")
    public Result<?> getRealLocation(@RequestParam(name = "vehicleNo", required = true) String vehicleNo) {
        if (StringUtils.isEmpty(vehicleNo)) {
            return Result.error("车牌号不允许为空!");
        }
        String ret = waybillRouteService.getRealLocation(vehicleNo);
        return Result.OK(ret);
    }


    @ApiOperation(value = "新运单实时轨迹", notes = "新运单实时轨迹")
    @GetMapping(value = "/getNewRealLocation")
//	@RequiresPermissions("shipping:track")
    public Result<?> getNewRealLocation(@RequestParam(name = "id", required = true) String id) {
        if (StringUtils.isEmpty(id)) {
            return Result.error("运单信息不允许为空!");
        }


        HyShippingNote shippingNote = hyShippingNoteService.getById(id);
        if (shippingNote == null) {
            return Result.error("运单信息不存在!");
        }

        HyVehicle vehicle = hyVehicleService.getById(shippingNote.getVehicleId());
        if (vehicle == null) {
            return Result.error("车辆信息不存在");
        }

        //Modified at 2023-08-01 for 运单实时轨迹修改为从接单到当前，如果要查实时位置用中交专用的实时位置查询接口
        //Calendar rightNow = Calendar.getInstance();
        //rightNow.setTime(new Date());
        //rightNow.add(Calendar.MINUTE,-10);
        String startTime = DateUtils.dateTimeToString(shippingNote.getStatusDtLoading());
        String endTime = DateUtils.dateTimeToString(new Date());
        WaybillRouteVO waybillRouteVO = waybillRouteService.getRouterPath(vehicle.getVehicleNumber(), startTime, endTime, "30");
        if (waybillRouteVO != null) {
            return Result.OK(
                    JSONObject.parseObject(JSONObject.toJSONString(waybillRouteVO))
            );
        }
        return Result.error("该运单实时轨迹查询失败！");
    }


    //endregion

    //region 撮合模式
    @ApiOperation(value = "查询运单支付凭证信息", notes = "查询运单支付凭证信息")
    @GetMapping(value = "/getPayBillInfo")
    public Result<?> getPayBillInfo(@RequestParam(name = "id", required = true) String id) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getById(id);
        if (hyShippingNote == null) {
            return Result.error("未找到运单数据");
        }
        HyShippingNoteBill bill = hyShippingNoteBillService.getOne(new QueryWrapper<HyShippingNoteBill>().eq("shipping_id", id));
        return Result.OK(bill);
    }

    @AutoLog(value = "上传支付凭证")
    @PutMapping(value = "/setPayBill")
    @Transactional
    public Result<?> setPayBill(@RequestBody Map<String, String> map) {
        String id = map.get("id");
        if (StringUtils.isEmpty(id)) {
            return Result.error("id参数错误");
        }
        String craccno = map.get("craccno");
        if (StringUtils.isEmpty(craccno)) {
            return Result.error("司机收款账户不能为空");
        }
        String bankCode = map.get("bankCode");
        if (StringUtils.isEmpty(bankCode)) {
            return Result.error("银行代码不能为空");
        }

        String bankHdImg = map.get("bankHdImg");
        if (StringUtils.isEmpty(bankHdImg)) {
            return Result.error("支付凭证不能为空");
        }

        HyShippingNote hyShippingNote = hyShippingNoteService.getById(id);
        if (hyShippingNote == null) {
            return Result.error("未找到运单数据");
        }

//		hyShippingNote.setPayBillUrl(payBillUrl);

        HyDriver driver = hyDriverService.getById(hyShippingNote.getDriverId());
        if (driver == null) {
            return Result.error("司机信息不存在");
        }
        HyVehicle vehicle = hyVehicleService.getById(hyShippingNote.getVehicleId());
        if (vehicle == null) {
            return Result.error("车辆信息不存在");
        }

        String shippingPayStatus = hyShippingNote.getShippingPayStatus();
        HyShippingNoteBill shippingNoteBill = null;
        if ("4".equals(shippingPayStatus)) {
            String shippingNoteBillNum = CodeUtil.getBillNum();
            shippingNoteBill = new HyShippingNoteBill();
            shippingNoteBill.setPayChannel("5"); //线下支付
            shippingNoteBill.setBillNum(shippingNoteBillNum);//设置支付流水单
            shippingNoteBill.setBillType("2");//2支付凭证(撮合模式)
            shippingNoteBill.setOrderId(hyShippingNote.getOrderId());
            shippingNoteBill.setShippingId(hyShippingNote.getId());
            shippingNoteBill.setShippingNoteNumber(hyShippingNote.getShippingNoteNumber());
            shippingNoteBill.setCompanyId(hyShippingNote.getCompanyId());
            shippingNoteBill.setPayType(hyShippingNote.getPayType());
            shippingNoteBill.setCarrierId(hyShippingNote.getCarrierId());
            shippingNoteBill.setDriverId(hyShippingNote.getDriverId());
            shippingNoteBill.setCarrier(driver.getDriverName());
            shippingNoteBill.setActualCarrierId(driver.getIdcard());
            shippingNoteBill.setVehicleId(hyShippingNote.getVehicleId());
            shippingNoteBill.setVehicleNumber(vehicle.getVehicleNumber());
            shippingNoteBill.setVehicleColorCode(vehicle.getVehiclePlateColorCode());

            //添加公司支付司机流水单
            BigDecimal costPayShipping = hyShippingNote.getCostPayShipping();//实际运费，分公司支付给司机或者车队长
            shippingNoteBill.setCraccno(craccno);
            shippingNoteBill.setCraccname(driver.getDriverName());
            shippingNoteBill.setCrlogaccno("");
            shippingNoteBill.setCrProv("");
            shippingNoteBill.setRespCode("4");
            shippingNoteBill.setRespSource("0");
            shippingNoteBill.setAmt(costPayShipping);//实际运费，分公司支付给司机或者车队长
            shippingNoteBill.setBankCode(bankCode);
            shippingNoteBill.setBankHdImg(bankHdImg);
            hyShippingNoteBillService.save(shippingNoteBill);
        } else {
            shippingNoteBill = hyShippingNoteBillService.getOne(new QueryWrapper<HyShippingNoteBill>().eq("shipping_id", id));
            shippingNoteBill.setCraccno(craccno);
            shippingNoteBill.setBankCode(bankCode);
            shippingNoteBill.setBankHdImg(bankHdImg);
            hyShippingNoteBillService.updateById(shippingNoteBill);
        }

        String realName = UserUtil.getLoginUser().getRName();
        hyShippingNote.setDzr(realName);//设置对账人
        hyShippingNote.setShippingPayStatus("6");
        hyShippingNote.setPayDtCheck(new Date());//对账完成时间
        hyShippingNoteService.updateById(hyShippingNote);
        return Result.OK("操作成功");
    }


    @AutoLog(value = "上传保单")
    @PutMapping(value = "/saveInsurance")
    public Result<?> saveInsurance(@RequestBody InsuranceApplyDto insuranceApplyDto) {

        if (StrUtil.isEmpty(insuranceApplyDto.getInsuranceCompany())) {
            return Result.error("保险公司全称不能为空");
        }

        if (StrUtil.isEmpty(insuranceApplyDto.getInsuranceNumber())) {
            return Result.error("保险公司代码不能为空");
        }

        if (StrUtil.isEmpty(insuranceApplyDto.getInsurancePolicy())) {
            return Result.error("保险单号不能为空");
        }

        if (StrUtil.isEmpty(insuranceApplyDto.getPdfUrl())) {
            return Result.error("保单文件不能为空");
        }

        if (StrUtil.isEmpty(insuranceApplyDto.getShippingId())) {
            return Result.error("该运单不存在");
        }

        return this.hyShippingNoteService.saveInsurance(insuranceApplyDto);
    }

    @AutoLog(value = "预览保单")
    @GetMapping(value = "/previewInsurance")
    public Result<?> previewInsurance(@RequestParam(name = "id") String id) {
        return this.hyShippingNoteService.previewInsurance(id);
    }

    //endregion


    //region 测试监管接口
    @Autowired
    private XinjiangReportService xinjiangReportService;

    @Autowired
    private AhReportService ahReportService;

    @Autowired
    private NxReportService nxReportService;

    @Autowired
    private HbReportService hbReportService;

    @Autowired
    private LiaoNingReportService liaoNingReportService;

    @Autowired
    private AmapService amapService;


    @PutMapping(value = "/testDingwei")
    public Result<?> testDingwei(@RequestBody HyShippingNote hyShippingNote) {
        RegeoDTO regeoDTO = this.amapService.coordinateRegeo("114.174644", "36.43717");
        return Result.OK(regeoDTO);
    }

    @PutMapping(value = "/testShippingNote")
    public Result<?> testUploadShippingNote(@RequestBody JSONObject json) {
        return this.hbReportService.reportTestShippingNote(json.toJSONString());
    }

    @PutMapping(value = "/testCapitalFlow")
    public Result<?> testUploadCapitalFlow(@RequestBody JSONObject json) {
        return this.hbReportService.reportTestCapitalFlow(json.toJSONString());
    }

    //测试宁夏监管驾驶员位置上报
    @PutMapping(value = "/testNxLocation")
    public Result<?> testNxLocation(@RequestBody HyShippingNote hyShippingNote) {
        if (StrUtil.isEmpty(hyShippingNote.getShippingNoteNumber())) {
            return Result.error("运单号不能为空");
        }

        HyShippingNote hyShippingNote1 = this.hyShippingNoteService.getByShippingNoteNumer(hyShippingNote.getShippingNoteNumber());
        if (null == hyShippingNote1) {
            return Result.error("运单不存在");
        }

        return this.hbReportService.uploadLocation(hyShippingNote1);
    }
    //endregion


    //测试企业上报
    @PutMapping(value = "/addEnterprise")
    public Result<?> testEnterprise(@RequestBody HyEnterprise hyEnterprise) {
        return this.liaoNingReportService.reportEnterprise("1");
    }

    @PutMapping(value = "/updateEnterprise")
    public Result<?> updateEnterprise(@RequestBody HyEnterprise hyEnterprise) {
        return this.liaoNingReportService.reportEnterprise("2");
    }
    //endregion


    @RequestMapping(value = "/exportXlsUrlGuoShui")
    public ModelAndView exportXlsUrlGuoShui(HttpServletRequest request, HyShippingNoteDTO shippingNoteDTO) {
        QueryWrapper<HyShippingNoteDTO> queryWrapper = new QueryWrapper();

        setQueryWrapper(shippingNoteDTO, queryWrapper);
        String selections = request.getParameter("selections");
        if (StringUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("hy_shipping_note.id", selectionList);
        }
        List<ShuiWuExportShippingNoteDTO> list = hyShippingNoteService.guoShuiShippingExport(queryWrapper);

        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        String title = "资金流水单";

        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, ShuiWuExportShippingNoteDTO.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", title));
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }
    //针对昆交切换支付后导出签字钱包无数据问题修改at20241112
    @RequestMapping(value = "/newExportXlsUrlGuoShui")
    public ModelAndView newExportXlsUrlGuoShui(HttpServletRequest request, HyShippingNoteDTO shippingNoteDTO) {
        QueryWrapper<HyShippingNoteDTO> queryWrapper = new QueryWrapper();

        setQueryWrapper(shippingNoteDTO, queryWrapper);
        String selections = request.getParameter("selections");
        if (StringUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("hy_shipping_note.id", selectionList);
        }
        List<ShuiWuExportShippingNoteDTO> list= hyShippingNoteService.guoShuiShippingExport(queryWrapper);
        List<ShuiWuExportShippingNoteDTO> newList = new ArrayList<>();
        ListIterator<ShuiWuExportShippingNoteDTO> iterator = list.listIterator();
        while (iterator.hasNext()){
            ShuiWuExportShippingNoteDTO next = iterator.next();
            if (StringUtils.isEmpty(next.getYsfwxsfkhhjzh())){
                String shippingNodeNum = next.getYdh();
                iterator.remove();
                HyShippingNote hyShippingNote = hyShippingNoteService.getByShippingNoteNumer(shippingNodeNum);
                QueryWrapper<HyShippingNoteDTO> queryWrapper1 = new QueryWrapper();
                setQueryWrapper(shippingNoteDTO, queryWrapper1);
                queryWrapper1.eq("hy_shipping_note.id",hyShippingNote.getId());
                newList.addAll(hyShippingNoteService.guoShuiShippingExport2(queryWrapper1));
            }else {
                newList.add(next);
            }
        }
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        String title = "资金流水单";
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, ShuiWuExportShippingNoteDTO.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", title));
        mv.addObject(NormalExcelConstants.DATA_LIST, newList);
        return mv;
    }


    @Autowired
    private KaiyunService kaiyunService;




    @AutoLog(value = "开运代开推送数据")
    @GetMapping(value = "/startPushKaiyun")
    public Result<?> pushKaiyun(HttpServletRequest req, @RequestParam(name = "shippingId") String shippingId) throws ParseException, IOException {

        if (!StringUtils.isNotBlank(shippingId)) {
            return Result.error("运单号为空!");
        }
        HyShippingNote shippingNote = hyShippingNoteService.getById(shippingId);
        if (shippingNote == null) {
            return Result.error("运单为空!");
        }
        HyOrder order = hyOrderService.getById(shippingNote.getOrderId());
        if (order == null) {
            return Result.error("货源为空!");
        }
        HyDriver driver = hyDriverService.getById(shippingNote.getDriverId());
        if (driver == null) {
            return Result.error("司机为空!");
        }
        HyVehicle vehicle = hyVehicleService.getById(shippingNote.getVehicleId());
        if (vehicle == null) {
            return Result.error("车辆为空!");
        }
//        HyShippingNoteBill shippingNoteBill = hyShippingNoteBillService.getBillByShippingId(shippingNote.getId());
//        if (shippingNoteBill == null) {
//            return Result.error("流水为空!");
//        }
        List<HyShippingNoteBill> shippingNoteBills = hyShippingNoteBillService.list(new LambdaQueryWrapper<HyShippingNoteBill>().eq(HyShippingNoteBill::getShippingId, shippingNote.getId()));
        if (CollUtil.isEmpty(shippingNoteBills)) {
            return Result.error(shippingNote.getShippingNoteNumber() + " ,资金流水不存在");
        }
        //2、接口调用顺序：1)新增车辆 2)新增承运人 3)新增驾驶员 4)发布货源 5)预约货源 6)支付流水-新增 7)编辑运单 8)推送轨迹 9)确认发货和到达
        Result<?> result = kaiyunService.addVehicle(req, vehicle, driver);

        //临时修补泰信不能上报问题atjxh240626
        if (!result.isSuccess()&&!result.getMessage().contains("已存在")) {
                shippingNote.setKyState("2");
                shippingNote.setKyMsg(result.getMessage());
                hyShippingNoteService.updateById(shippingNote);
                return Result.error(result.getMessage());
        }
        Result<?> result1 = kaiyunService.addApiCarrier(req, driver);
        if (!result1.isSuccess()&&!result1.getMessage().contains("已存在")) {

                shippingNote.setKyState("2");
                shippingNote.setKyMsg(result1.getMessage());
                hyShippingNoteService.updateById(shippingNote);
                return Result.error(result1.getMessage());
        }
        Result<?> result2 = kaiyunService.addDriver(req, driver);
        if (!result2.isSuccess()&&!result2.getMessage().contains("已存在")) {


                shippingNote.setKyState("2");
                shippingNote.setKyMsg(result2.getMessage());
                hyShippingNoteService.updateById(shippingNote);
                return Result.error(result2.getMessage());
        }
        Result<?> result3 = kaiyunService.addOrder(req, order);
        if (!result3.isSuccess()&&!result3.getMessage().contains("已存在")) {


                shippingNote.setKyState("2");
                shippingNote.setKyMsg(result3.getMessage());
                hyShippingNoteService.updateById(shippingNote);
                return Result.error(result3.getMessage());
        }
        Result<?> result4 = kaiyunService.addOrEditShippingNote(req, shippingNote, shippingNoteBills, driver, vehicle);
        if (!result4.isSuccess()) {
            shippingNote.setKyState("2");
            shippingNote.setKyMsg(result4.getMessage());
            hyShippingNoteService.updateById(shippingNote);
            return Result.error(result4.getMessage());
        }
        Result<?> result5 = kaiyunService.addBill(req, shippingNoteBills, shippingNote);
        if (!result5.isSuccess()) {
            shippingNote.setKyState("2");
            shippingNote.setKyMsg(result5.getMessage());
            hyShippingNoteService.updateById(shippingNote);
            return Result.error(result5.getMessage());
        }
        Result<?> result6 = kaiyunService.addTrack(req, vehicle, shippingNote);
        if (!result6.isSuccess()) {
            shippingNote.setKyState("2");
            shippingNote.setKyMsg(result6.getMessage());
            hyShippingNoteService.updateById(shippingNote);
            return Result.error(result6.getMessage());
        }
        Result<?> taxwaybillconfirm = kaiyunService.taxwaybillconfirm(shippingNote.getShippingNoteNumber(), "0");
        if (!taxwaybillconfirm.isSuccess()) {
            shippingNote.setKyState("2");
            shippingNote.setKyMsg(taxwaybillconfirm.getMessage());
            hyShippingNoteService.updateById(shippingNote);
            return Result.error(taxwaybillconfirm.getMessage());
        }
        Result<?> taxwaybillconfirm2 = kaiyunService.taxwaybillconfirm(shippingNote.getShippingNoteNumber(), "1");
        if (!taxwaybillconfirm.isSuccess()) {
            shippingNote.setKyState("2");
            shippingNote.setKyMsg(taxwaybillconfirm2.getMessage());
            hyShippingNoteService.updateById(shippingNote);
            return Result.error(taxwaybillconfirm2.getMessage());
        }else{
            shippingNote.setKyState("1");
            shippingNote.setKyMsg(taxwaybillconfirm.getMessage());
            hyShippingNoteService.updateById(shippingNote);
        }

        return Result.OK();
    }

    @AutoLog(value = "批量删除开运流水")
    @PostMapping(value = "/delKaiyunBills")
    public Result<?> delKaiyunBills(HttpServletRequest req,@RequestParam(name = "ids", required = true) String ids) throws ParseException, IOException {
        if (StringUtils.isBlank(ids)) {
            return Result.error("运单不能为空!");
        }
        List<HyShippingNote> hyShippingNotes = hyShippingNoteService.listByIdsForUpdate(Arrays.asList(ids.split(",")));

        for (HyShippingNote shippingNote : hyShippingNotes) {
            List<HyShippingNoteBill> shippingNoteBills = hyShippingNoteBillService.list(new LambdaQueryWrapper<HyShippingNoteBill>().eq(HyShippingNoteBill::getShippingId, shippingNote.getId()));
            if (CollUtil.isEmpty(shippingNoteBills)) {
                return Result.error(shippingNote.getShippingNoteNumber() + " ,资金流水不存在");
            }
//            HyShippingNoteBill shippingNoteBill = hyShippingNoteBillService.getBillByShippingId(shippingNote.getId());
//            if (shippingNoteBill == null) {
//                return Result.error("流水为空!");
//            }
            for (HyShippingNoteBill shippingNoteBill : shippingNoteBills) {
                Result<?> result5 = kaiyunService.delBill(shippingNoteBill);
                if (!result5.isSuccess()) {
                    shippingNote.setKyState("2");
                    shippingNote.setKyMsg(result5.getMessage());
                    hyShippingNoteService.updateById(shippingNote);
                    return Result.error(result5.getMessage());
                }
            }

        }
        return Result.OK();
    }
    @AutoLog(value = "批量添加开运流水")
    @PostMapping(value = "/addKaiyunBills")
    public Result<?> addKaiyunBills(HttpServletRequest req,@RequestParam(name = "ids", required = true) String ids) throws ParseException, IOException {
        if (StringUtils.isBlank(ids)) {
            return Result.error("运单不能为空!");
        }
        List<HyShippingNote> hyShippingNotes = hyShippingNoteService.listByIdsForUpdate(Arrays.asList(ids.split(",")));

        for (HyShippingNote shippingNote : hyShippingNotes) {

            List<HyShippingNoteBill> shippingNoteBills = hyShippingNoteBillService.list(new LambdaQueryWrapper<HyShippingNoteBill>().eq(HyShippingNoteBill::getShippingId, shippingNote.getId()));
            if (CollUtil.isEmpty(shippingNoteBills)) {
                return Result.error(shippingNote.getShippingNoteNumber() + " ,资金流水不存在");
            }

//            HyShippingNoteBill shippingNoteBill = hyShippingNoteBillService.getBillByShippingId(shippingNote.getId());
//            if (shippingNoteBill == null) {
//                return Result.error("流水为空!");
//            }
            Result<?> result5 = kaiyunService.addBill(req,shippingNoteBills,shippingNote);
            if (!result5.isSuccess()) {
                shippingNote.setKyState("2");
                shippingNote.setKyMsg(result5.getMessage());
                hyShippingNoteService.updateById(shippingNote);
                return Result.error(result5.getMessage());
            }
        }
        return Result.OK();
    }

    @AutoLog(value = "开运代开推送数据")
    @PostMapping(value = "/startPushKaiyunPl")
    public Result<?> startPushKaiyunPl(HttpServletRequest req,@RequestParam(name = "ids", required = true) String ids) throws ParseException, IOException {

        if (StringUtils.isBlank(ids)) {
            return Result.error("ids不能为空!");
        }
        List<HyShippingNote> hyShippingNotes = hyShippingNoteService.listByIdsForUpdate(Arrays.asList(ids.split(",")));

        for (HyShippingNote shippingNote : hyShippingNotes) {
            if (shippingNote == null) {
                return Result.error("运单为空!");
            }
            HyOrder order = hyOrderService.getById(shippingNote.getOrderId());
            if (order == null) {
                return Result.error("货源为空!");
            }
            HyDriver driver = hyDriverService.getById(shippingNote.getDriverId());
            if (driver == null) {
                return Result.error("司机为空!");
            }
            HyVehicle vehicle = hyVehicleService.getById(shippingNote.getVehicleId());
            if (vehicle == null) {
                return Result.error("车辆为空!");
            }

            List<HyShippingNoteBill> shippingNoteBills = hyShippingNoteBillService.list(new LambdaQueryWrapper<HyShippingNoteBill>().eq(HyShippingNoteBill::getShippingId, shippingNote.getId()));
            if (CollUtil.isEmpty(shippingNoteBills)) {
                return Result.error(shippingNote.getShippingNoteNumber() + " ,资金流水不存在");
            }

//            HyShippingNoteBill shippingNoteBill = hyShippingNoteBillService.getBillByShippingId(shippingNote.getId());
//            if (shippingNoteBill == null) {
//                return Result.error("流水为空!");
//            }
            //2、接口调用顺序：1)新增车辆 2)新增承运人 3)新增驾驶员 4)发布货源 5)预约货源 6)支付流水-新增 7)编辑运单 8)推送轨迹 9)确认发货和到达
            Result<?> result = kaiyunService.addVehicle(req, vehicle, driver);

            if (!result.isSuccess()) {
                shippingNote.setKyState("2");
                shippingNote.setKyMsg(result.getMessage());
                hyShippingNoteService.updateById(shippingNote);

                return Result.error(result.getMessage());
            }
            Result<?> result1 = kaiyunService.addApiCarrier(req, driver);
            if (!result1.isSuccess()) {
                shippingNote.setKyState("2");
                shippingNote.setKyMsg(result1.getMessage());
                hyShippingNoteService.updateById(shippingNote);
                return Result.error(result1.getMessage());
            }
            Result<?> result2 = kaiyunService.addDriver(req, driver);
            if (!result2.isSuccess()) {
                shippingNote.setKyState("2");
                shippingNote.setKyMsg(result2.getMessage());
                hyShippingNoteService.updateById(shippingNote);
                return Result.error(result2.getMessage());
            }
            Result<?> result3 = kaiyunService.addOrder(req, order);
            if (!result3.isSuccess()) {
                shippingNote.setKyState("2");
                shippingNote.setKyMsg(result3.getMessage());
                hyShippingNoteService.updateById(shippingNote);
                return Result.error(result3.getMessage());
            }
            Result<?> result4 = kaiyunService.addOrEditShippingNote(req, shippingNote, shippingNoteBills, driver, vehicle);
            if (!result4.isSuccess()) {
                shippingNote.setKyState("2");
                shippingNote.setKyMsg(result4.getMessage());
                hyShippingNoteService.updateById(shippingNote);
                return Result.error(result4.getMessage());
            }
            Result<?> result5 = kaiyunService.addBill(req, shippingNoteBills, shippingNote);
            if (!result5.isSuccess()) {
                shippingNote.setKyState("2");
                shippingNote.setKyMsg(result5.getMessage());
                hyShippingNoteService.updateById(shippingNote);
                return Result.error(result5.getMessage());
            }
            Result<?> result6 = kaiyunService.addTrack(req, vehicle, shippingNote);
            if (!result6.isSuccess()) {
                shippingNote.setKyState("2");
                shippingNote.setKyMsg(result6.getMessage());
                hyShippingNoteService.updateById(shippingNote);
                return Result.error(result6.getMessage());
            }
            Result<?> taxwaybillconfirm = kaiyunService.taxwaybillconfirm(shippingNote.getShippingNoteNumber(), "0");
            if (!taxwaybillconfirm.isSuccess()) {
                shippingNote.setKyState("2");
                shippingNote.setKyMsg(taxwaybillconfirm.getMessage());
                hyShippingNoteService.updateById(shippingNote);
                return Result.error(taxwaybillconfirm.getMessage());
            }
            Result<?> taxwaybillconfirm2 = kaiyunService.taxwaybillconfirm(shippingNote.getShippingNoteNumber(), "1");
            if (!taxwaybillconfirm.isSuccess()) {
                shippingNote.setKyState("2");
                shippingNote.setKyMsg(taxwaybillconfirm2.getMessage());
                hyShippingNoteService.updateById(shippingNote);
                return Result.error(taxwaybillconfirm2.getMessage());
            }else{
                shippingNote.setKyState("1");
                shippingNote.setKyMsg(taxwaybillconfirm.getMessage());
                hyShippingNoteService.updateById(shippingNote);
            }
        }
        return Result.OK();
    }
    /**
     * 一键补单
     */
    @PostMapping("/copyShippingNote")
    public Result<?> copyShippingNote(@RequestBody HyShippingNoteAndOrder shippingNote) {

        HyDriver driver = hyDriverService.getDriverById(shippingNote.getDriverId());
        HyVehicle vehicle = hyVehicleService.getById(shippingNote.getVehicleId());
        HyCustomer customer = customerService.getById(shippingNote.getCustomerId());
        HyCustomerConfig hyCustomerConfig = customerConfigService.getByCustomerId(shippingNote.getCustomerId());
        //查找司机默认银行卡
        /*HyDriverBank defaultDriverBank = hyDriverBankService.getDefaultDriverBank(shippingNote.getDriverId());
        String driverBankId = "";
        if (defaultDriverBank != null) {
            driverBankId = defaultDriverBank.getId();
        }*/
        if (StringUtils.isEmpty(shippingNote.getOrderMode())){
            shippingNote.setOrderMode("1");
        }
        //司机 货主添加关系表
        hyDriverCustomerService.addDriverCustomer(shippingNote.getDriverId(), customer.getId());
        hyDriverCustomerService.addVehicleCustomer(shippingNote.getVehicleId(), customer.getId());
        /*HyOrder order = hyShippingNoteService.saveOrder(shippingNote,customer, hyCustomerCompany);
        if (order == null) {
            return Result.error("补单异常,货源创建失败");
        }*/
        HyOrderDTO hyOrderDTO = toOrder(shippingNote,customer,hyCustomerConfig);
        Result result = hyOrderService.addOrder(hyOrderDTO);
        if (!result.isSuccess()) {
            return Result.error("补单失败");
        }
        HyOrder order = (HyOrder) redisUtil.get("hyOrderNew");
        Result r = hyShippingNoteService.addByOrder(order, driver, vehicle, null, "", "", shippingNote.getDriverBankId());
        if (r.isSuccess()) {
            return Result.OK();
        } else {
            hyOrderService.removeById(order.getId());
            log.error(r.getMessage());
            return Result.error("一键补单失败");
        }
    }


        private HyOrderDTO toOrder(HyShippingNoteAndOrder hyShippingNote, HyCustomer customer, HyCustomerConfig hyCustomerConfig) {
            HyOrderDTO hyOrderDTO = new HyOrderDTO();

            HyCustomerAddressSend customerAddressSend = customerAddressSendService.getById(hyShippingNote.getHyShippingNoteSendAddressList().get(0).getAddressSendId());
            HyCustomerAddressReceive addressReceive = customerAddressReceiveService.getById(hyShippingNote.getHyShippingNoteReceiveAddressList().get(0).getAddressReceiveId());
            HyShippingNoteSendAddress hyShippingNoteSendAddress = hyShippingNote.getHyShippingNoteSendAddressList().get(0);
            HyShippingNoteReceiveAddress hyShippingNoteReceiveAddress = hyShippingNote.getHyShippingNoteReceiveAddressList().get(0);

            List<HyOrderSendAddress> hyOrderSendAddressList = new ArrayList<>();
            List<HyOrderReceiveAddress> hyOrderReceiveAddressList= new ArrayList<>();
            hyOrderDTO.setCustomerId(customer.getId());
            if (StringUtils.isNotEmpty(hyShippingNote.getKhdh())){
                hyOrderDTO.setKhdh(hyShippingNote.getKhdh());
            }
            hyOrderDTO.setOrderType("1");
            hyOrderDTO.setOrderMode(hyShippingNote.getOrderMode());
            if (StringUtils.isNotEmpty(hyShippingNote.getBusinessTypeCode())){
                hyOrderDTO.setBusinessTypeCode(hyShippingNote.getBusinessTypeCode());
            }
            hyOrderDTO.setGoodsUnit(hyShippingNote.getGoodsUnit());
            hyOrderDTO.setDescriptionOfGoods(hyShippingNote.getDescriptionOfGoods());
            hyOrderDTO.setCargoTypeClassificationCode(hyShippingNote.getCargoTypeClassificationCode());
            hyOrderDTO.setPayType(hyShippingNote.getPayType());
            if (hyShippingNote.getPayType().equals("2")){
                hyOrderDTO.setCarrierId(hyShippingNote.getCarrierId());
                hyOrderDTO.setCarrierFeeType(hyShippingNote.getCarrierFeeType());
                hyOrderDTO.setCarrierUnitFee(hyShippingNote.getCarrierUnitFee());
            }
            hyOrderDTO.setLossGoodsUnitPrice(hyShippingNote.getLossGoodsUnitPrice());
            hyOrderDTO.setShippingUnitPrice(hyShippingNote.getShippingUnitPrice());
            hyOrderDTO.setShippingType(hyShippingNote.getShippingType());
            if (StringUtils.isNotEmpty(hyShippingNote.getCustomerShippingType())){
                hyOrderDTO.setCustomerShippingType(hyShippingNote.getCustomerShippingType());
            }
            hyOrderDTO.setLossType(hyShippingNote.getLossType());
            hyOrderDTO.setLossProportion(hyShippingNote.getLossProportion());
            hyOrderDTO.setExamineStatus("1");
            hyOrderDTO.setExamineDate(new Date());
            hyOrderDTO.setOrderStatus("2");//已发布
            hyOrderDTO.setDtPublish(new Date());
            hyOrderDTO.setIzUsedGas(hyShippingNote.getIzUsedGas());
            if (hyOrderDTO.getIzUsedGas().equals("1")){
                hyOrderDTO.setGasRechargeAmount(hyShippingNote.getGasRechargeAmount());
            }
            //hyOrderDTO.setOrderImportFlag("888");
           /* QueryWrapper<SysDict> queryWrapper = new QueryWrapper();
            queryWrapper.eq("dict_code","yn");
            SysDict dict = sysDictService.getOne(queryWrapper);
            List<SysDictItem> list = sysDictItemService.selectItemsByMainId(dict.getId());
            List<String> stringList = new ArrayList<>();
            for (SysDictItem sysDictItem : list) {
                stringList.add(sysDictItem.getItemValue());
            }
            if (!stringList.contains("888")){
                SysDictItem sysDictItem = new SysDictItem();
                sysDictItem.setItemValue("888");
                sysDictItem.setDictId(dict.getId());
                sysDictItem.setCreateTime(new Date());
                sysDictItem.setCreateBy(userUtil.getUser().getUsername());
                sysDictItem.setStatus(1);
                sysDictItem.setItemText("一键补单导入");
                sysDictItem.setDescription("一键补单导入");
                sysDictItem.setSortOrder(3);
                sysDictItemService.save(sysDictItem);
            }*/

            hyOrderDTO.setUnloadingFee(hyShippingNote.getUnloadingFee());
            hyOrderDTO.setInformationFee(hyShippingNote.getInformationFee());
            hyOrderDTO.setServiceFee(hyShippingNote.getServiceFee());
            if (StringUtils.isNotEmpty(hyShippingNote.getAgentId())){
                hyOrderDTO.setAgentId(hyShippingNote.getAgentId());
                hyOrderDTO.setAgentPrice(hyShippingNote.getAgentPrice());
            }
            hyOrderDTO.setCreateTime(new Date());
            hyOrderDTO.setCreateBy(userUtil.getLoginUser().getUsername());
            hyOrderDTO.setOrderSetting(false);
            hyOrderDTO.setBz(hyShippingNote.getBz());
            hyOrderDTO.setUnloadingBz(hyShippingNote.getUnloadingBz());
            if (hyShippingNote.getPayType().equals("3")){
                hyOrderDTO.setPreType(hyShippingNote.getPreType());
                hyOrderDTO.setPreUnitFee(hyShippingNote.getPreUnitFee());
            }
            if (StringUtils.isNotEmpty(hyShippingNote.getKeyword())){
                hyOrderDTO.setKeyword(hyShippingNote.getKeyword());
            }
            if (StringUtils.isNotEmpty(hyShippingNote.getIntroducer())){
                hyOrderDTO.setIntroducer(hyShippingNote.getIntroducer());
            }
            if (StringUtils.isNotEmpty(hyShippingNote.getDispatcher())){
                hyOrderDTO.setDispatcher(hyShippingNote.getDispatcher());
            }
            hyOrderDTO.setCostServiceId(hyShippingNote.getCostServiceId());
            hyOrderDTO.setIzOrderSet(hyShippingNote.getIzOrderSet());
            //如果未开启货源参数则去取货主参数中的值进行赋值
            if (hyShippingNote.getIzOrderSet().equals("1")){
                hyOrderDTO.setIzDriverMl(hyShippingNote.getIzDriverMl());
                if (hyShippingNote.getIzDriverMl().equals("1")){
                    hyOrderDTO.setDriverMlWs(hyShippingNote.getDriverMlWs());
                    hyOrderDTO.setDriverMlFw(hyShippingNote.getDriverMlFw());
                }
                hyOrderDTO.setIzZd(hyShippingNote.getIzZd());
                if (hyShippingNote.getIzZd().equals("1")){
                    hyOrderDTO.setZdJs(hyShippingNote.getZdJs());
                }
                hyOrderDTO.setIzDriverPayset(hyShippingNote.getIzDriverPayset());
            }else {
                hyOrderDTO.setIzDriverMl(hyCustomerConfig.getIzDriverMl());
                if (hyCustomerConfig.getIzDriverMl().equals("1")){
                    hyOrderDTO.setDriverMlWs(hyCustomerConfig.getDriverMlWs());
                    hyOrderDTO.setDriverMlFw("10");
                }
                hyOrderDTO.setIzZd(hyCustomerConfig.getIzZd());
                if (hyCustomerConfig.getIzZd().equals("1")){
                    hyOrderDTO.setZdJs(hyCustomerConfig.getZdJs().toString());
                }
                hyOrderDTO.setIzDriverPayset(hyCustomerConfig.getIzDriverPayset());
            }




            //处理发货数据
            HyOrderSendAddress orderSendAddress = new HyOrderSendAddress();
            orderSendAddress.setAddressSendId(hyShippingNoteSendAddress.getAddressSendId());
            orderSendAddress.setIzDest(true);
            if (hyShippingNote.getSendDate()!=null){
                orderSendAddress.setSendDate(hyShippingNoteSendAddress.getSendDate());
            }
            orderSendAddress.setCustomerId(hyShippingNoteSendAddress.getCustomerId());
            orderSendAddress.setSendAddressName(hyShippingNoteSendAddress.getSendAddressName());
            orderSendAddress.setSendAddress(hyShippingNoteSendAddress.getSendAddress());
            orderSendAddress.setSendLatitude(hyShippingNoteSendAddress.getSendLatitude());
            orderSendAddress.setSendLongitude(hyShippingNoteSendAddress.getSendLongitude());
            orderSendAddress.setSendAreaCode(hyShippingNoteSendAddress.getSendAreaCode());
            orderSendAddress.setSendContactName(hyShippingNoteSendAddress.getSendContactName());
            orderSendAddress.setSendContactTel(hyShippingNoteSendAddress.getSendContactTel());
            if (StringUtils.isNotEmpty(customerAddressSend.getContactCredit())){
                orderSendAddress.setSendContactCredit(customerAddressSend.getContactCredit());
            }
            orderSendAddress.setSortNum(1);
            orderSendAddress.setCreateBy(userUtil.getLoginUser().getUsername());
            orderSendAddress.setCreateTime(new Date());
            hyOrderSendAddressList.add(orderSendAddress);
            //处理收货数据
            HyOrderReceiveAddress receiveAddress = new HyOrderReceiveAddress();
            receiveAddress.setAddressReceiveId(hyShippingNoteReceiveAddress.getAddressReceiveId());
            receiveAddress.setIzDest(true);
            receiveAddress.setReceiveAddress(hyShippingNoteReceiveAddress.getReceiveAddress());
            receiveAddress.setReceiveAddressName(hyShippingNoteReceiveAddress.getReceiveAddressName());
            receiveAddress.setReceiveAreaCode(hyShippingNoteReceiveAddress.getReceiveAreaCode());
            receiveAddress.setReceiveContactName(hyShippingNoteReceiveAddress.getReceiveContactName());
            receiveAddress.setReceiveContactTel(hyShippingNoteReceiveAddress.getReceiveContactTel());
            receiveAddress.setReceiveLatitude(hyShippingNoteReceiveAddress.getReceiveLatitude());
            receiveAddress.setReceiveLongitude(hyShippingNoteReceiveAddress.getReceiveLongitude());
            receiveAddress.setCustomerId(hyShippingNoteReceiveAddress.getCustomerId());
            if (hyShippingNote.getReceiveDate()!=null){
                receiveAddress.setReceiveDate(hyShippingNoteReceiveAddress.getReceiveDate());
            }
            if (StringUtils.isNotEmpty(addressReceive.getContactCredit())){
                receiveAddress.setReceiveContactCredit(addressReceive.getContactCredit());
            }
            receiveAddress.setCreateBy(userUtil.getLoginUser().getUsername());
            receiveAddress.setCreateTime(new Date());
            receiveAddress.setSortNum(1);
            hyOrderReceiveAddressList.add(receiveAddress);
            hyOrderDTO.setHyOrderSendAddressList(hyOrderSendAddressList);
            hyOrderDTO.setHyOrderReceiveAddressList(hyOrderReceiveAddressList);
            return hyOrderDTO;
        }

    @GetMapping("/getCountList")
    public Result<?> getCountList(){

        List<ShippingNoteCountListDTO> countList = new ArrayList<>();
        QueryWrapper<HyShippingNote> queryWrapper9 = new QueryWrapper<>();
        if (userUtil.isCustomerAdmin()) {
            queryWrapper9.in("customer_id", userUtil.getCustomerAdminRelationIdList());
        }else if (userUtil.getLoginUser().getUType().equals(UserTypeEnum.货主.getCode())){
            HyCustomer customer = userUtil.getCustomer();
            queryWrapper9.eq("customer_id",customer.getId());
        }
        ShippingNoteCountListDTO dto9 = new ShippingNoteCountListDTO();
        int count9 = hyShippingNoteService.count(queryWrapper9);
        dto9.setCount(count9);
        dto9.setKey("");
        dto9.setTitle("全部");
        countList.add(dto9);

        QueryWrapper<HyShippingNote> queryWrapper = new QueryWrapper<>();
        if (userUtil.isCustomerAdmin()) {
            queryWrapper.in("customer_id", userUtil.getCustomerAdminRelationIdList());
        }else if (userUtil.getLoginUser().getUType().equals(UserTypeEnum.货主.getCode())){
            HyCustomer customer = userUtil.getCustomer();
            queryWrapper.eq("customer_id",customer.getId());
        }
        queryWrapper.eq("shipping_status",0);
        ShippingNoteCountListDTO dto = new ShippingNoteCountListDTO();
        int count0 = hyShippingNoteService.count(queryWrapper);
        dto.setCount(count0);
        dto.setKey("0");
        dto.setTitle(ShippingStatus.待接单.name());
        countList.add(dto);

        QueryWrapper<HyShippingNote> queryWrapper1 = new QueryWrapper<>();
        if (userUtil.isCustomerAdmin()) {
            queryWrapper1.in("customer_id", userUtil.getCustomerAdminRelationIdList());
        }else if (userUtil.getLoginUser().getUType().equals(UserTypeEnum.货主.getCode())){
            HyCustomer customer = userUtil.getCustomer();
            queryWrapper1.eq("customer_id",customer.getId());
        }
        queryWrapper1.eq("shipping_status",1);
        int count1 = hyShippingNoteService.count(queryWrapper1);
        ShippingNoteCountListDTO dto1 = new ShippingNoteCountListDTO();
        dto1.setCount(count1);
        dto1.setKey("1");
        dto1.setTitle(ShippingStatus.已接单.name());
        countList.add(dto1);
       /* QueryWrapper<HyShippingNote> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("shipping_status",2);
        int count2 = hyShippingNoteService.count(queryWrapper2);
        ShippingNoteCountListDTO dto2 = new ShippingNoteCountListDTO();
        dto2.setCount(count2);
        dto2.setKey("2");
        dto2.setTitle(ShippingStatus.装货中.name());
        countList.add(dto2);*/
        QueryWrapper<HyShippingNote> queryWrapper3 = new QueryWrapper<>();
        if (userUtil.isCustomerAdmin()) {
            queryWrapper3.in("customer_id", userUtil.getCustomerAdminRelationIdList());
        }else if (userUtil.getLoginUser().getUType().equals(UserTypeEnum.货主.getCode())){
            HyCustomer customer = userUtil.getCustomer();
            queryWrapper3.eq("customer_id",customer.getId());
        }
        queryWrapper3.eq("shipping_status",3);
        int count3 = hyShippingNoteService.count(queryWrapper3);
        ShippingNoteCountListDTO dto3 = new ShippingNoteCountListDTO();
        dto3.setCount(count3);
        dto3.setKey("3");
        dto3.setTitle(ShippingStatus.运输中.name());
        countList.add(dto3);
        QueryWrapper<HyShippingNote> queryWrapper4= new QueryWrapper<>();
        if (userUtil.isCustomerAdmin()) {
            queryWrapper4.in("customer_id", userUtil.getCustomerAdminRelationIdList());
        }else if (userUtil.getLoginUser().getUType().equals(UserTypeEnum.货主.getCode())){
            HyCustomer customer = userUtil.getCustomer();
            queryWrapper4.eq("customer_id",customer.getId());
        }
        queryWrapper4.eq("shipping_status",4);
        int count4 = hyShippingNoteService.count(queryWrapper4);
        ShippingNoteCountListDTO dto4 = new ShippingNoteCountListDTO();
        dto4.setCount(count4);
        dto4.setKey("4");
        dto4.setTitle(ShippingStatus.已交货.name());
        countList.add(dto4);
        ShippingNoteCountListDTO dto5 = new ShippingNoteCountListDTO();
        dto5.setKey("5");
        dto5.setTitle(ShippingStatus.已签收.name());
        dto5.setCount(0);
        countList.add(dto5);
        QueryWrapper<HyShippingNote> queryWrapper8= new QueryWrapper<>();
        queryWrapper8.eq("shipping_status",8);
        if (userUtil.isCustomerAdmin()) {
            queryWrapper8.in("customer_id", userUtil.getCustomerAdminRelationIdList());
        }else if (userUtil.getLoginUser().getUType().equals(UserTypeEnum.货主.getCode())){
            HyCustomer customer = userUtil.getCustomer();
            queryWrapper8.eq("customer_id",customer.getId());
        }
        int count8 = hyShippingNoteService.count(queryWrapper8);
        ShippingNoteCountListDTO dto8 = new ShippingNoteCountListDTO();
        dto8.setCount(count8);
        dto8.setKey("8");
        dto8.setTitle(ShippingStatus.已作废.name());
        countList.add(dto8);
        return Result.OK(countList);
    }


}


